52 lines
1.4 KiB
C#
Raw Normal View History

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]
private FiniteStateMachine _enemtStateMachine;
private Transform _target;
void Start()
{
2020-03-08 20:41:22 +01:00
_target = AtomTags.FindByTag(_tagToTarget.Value).transform;
2020-03-08 12:32:41 +01:00
_enemtStateMachine.Begin();
}
void Update()
{
2020-03-08 20:41:22 +01:00
var inRange = _shotRange.Value >= Vector3.Distance(_target.position, transform.position);
if (_enemtStateMachine.Value != "ATTACKING" && inRange)
2020-03-08 12:32:41 +01:00
{
_enemtStateMachine.Dispatch("ATTACK");
}
2020-03-08 20:41:22 +01:00
else if (_enemtStateMachine.Value != "CHASING" && !inRange)
2020-03-08 12:32:41 +01:00
{
_enemtStateMachine.Dispatch("CHASE");
}
2020-03-08 20:41:22 +01:00
var direction = _target.position - transform.position;
if (_enemtStateMachine.Value == "CHASING")
{
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
}
}