2020-03-08 12:32:41 +01:00
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityAtoms.BaseAtoms;
|
|
|
|
|
using UnityAtoms.Tags;
|
|
|
|
|
using UnityAtoms.FSM;
|
|
|
|
|
|
|
|
|
|
public class EnemyState : MonoBehaviour
|
|
|
|
|
{
|
|
|
|
|
[SerializeField]
|
|
|
|
|
private StringReference _tagToTarget;
|
|
|
|
|
|
|
|
|
|
[SerializeField]
|
|
|
|
|
private FloatReference _shotRange = new FloatReference(5f);
|
|
|
|
|
|
|
|
|
|
[SerializeField]
|
2020-03-09 00:16:40 +01:00
|
|
|
|
private FiniteStateMachineReference _enemyStateMachineRef;
|
2020-03-08 12:32:41 +01:00
|
|
|
|
|
|
|
|
|
private Transform _target;
|
|
|
|
|
|
|
|
|
|
void Start()
|
|
|
|
|
{
|
2020-03-08 20:41:22 +01:00
|
|
|
|
_target = AtomTags.FindByTag(_tagToTarget.Value).transform;
|
2020-03-09 00:16:40 +01:00
|
|
|
|
_enemyStateMachineRef.Machine.Begin();
|
2020-03-08 12:32:41 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void Update()
|
|
|
|
|
{
|
2020-03-08 20:41:22 +01:00
|
|
|
|
var inRange = _shotRange.Value >= Vector3.Distance(_target.position, transform.position);
|
2020-03-09 00:16:40 +01:00
|
|
|
|
if (_enemyStateMachineRef.Machine.Value != "ATTACKING" && inRange)
|
2020-03-08 12:32:41 +01:00
|
|
|
|
{
|
2020-03-09 00:16:40 +01:00
|
|
|
|
_enemyStateMachineRef.Machine.Dispatch("ATTACK");
|
2020-03-08 12:32:41 +01:00
|
|
|
|
}
|
2020-03-09 00:16:40 +01:00
|
|
|
|
else if (_enemyStateMachineRef.Machine.Value != "CHASING" && !inRange)
|
2020-03-08 12:32:41 +01:00
|
|
|
|
{
|
2020-03-09 00:16:40 +01:00
|
|
|
|
_enemyStateMachineRef.Machine.Dispatch("CHASE");
|
2020-03-08 12:32:41 +01:00
|
|
|
|
}
|
2020-03-08 20:41:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var direction = _target.position - transform.position;
|
2020-03-09 00:16:40 +01:00
|
|
|
|
if (_enemyStateMachineRef.Machine.Value == "CHASING")
|
2020-03-08 20:41:22 +01:00
|
|
|
|
{
|
|
|
|
|
GetComponent<Rigidbody2D>().velocity = direction.normalized * 5f;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
|
|
|
|
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
|
2020-03-08 12:32:41 +01:00
|
|
|
|
}
|
|
|
|
|
}
|