44 lines
1.6 KiB
C#
Raw Normal View History

2020-03-11 21:11:27 +01:00
using UnityEngine;
using UnityAtoms.BaseAtoms;
using UnityAtoms.Tags;
using UnityAtoms.FSM;
2020-03-18 02:00:18 +01:00
namespace UnityAtoms.Examples
2020-03-11 21:11:27 +01:00
{
2020-03-18 02:00:18 +01:00
public class EnemyMovement : MonoBehaviour
{
[SerializeField]
private StringReference _tagToTarget;
2020-03-11 21:11:27 +01:00
2020-03-18 02:00:18 +01:00
[SerializeField]
private FloatReference _shootingRange = new FloatReference(5f);
2020-03-11 21:11:27 +01:00
2020-03-18 02:00:18 +01:00
[SerializeField]
private FloatReference _moveSpeedMultiplier = new FloatReference(2f);
2020-03-11 21:11:27 +01:00
2020-03-18 02:00:18 +01:00
[SerializeField]
private FiniteStateMachineReference _enemyState;
2020-03-11 21:11:27 +01:00
2020-03-18 02:00:18 +01:00
void Awake()
2020-03-15 23:18:29 +01:00
{
2020-03-18 02:00:18 +01:00
Transform target = null;
AtomTags.OnInitialization(() => target = AtomTags.FindByTag(_tagToTarget.Value).transform);
var body = GetComponent<Rigidbody2D>();
_enemyState.Machine.OnUpdate((deltaTime, value) =>
2020-03-15 23:18:29 +01:00
{
2020-03-18 02:00:18 +01:00
if (target)
{
body.Move((target.position - transform.position), value == "CHASING" ? 2f : 0f, deltaTime);
}
else
{
body.Move(Vector2.zero, 0f, deltaTime);
}
}, gameObject);
_enemyState.Machine.DispatchWhen(command: "ATTACK", (value) => target != null && value == "CHASING" && (_shootingRange.Value >= Vector3.Distance(target.position, transform.position)), gameObject);
_enemyState.Machine.DispatchWhen(command: "CHASE", (value) => target != null && value == "ATTACKING" && (_shootingRange.Value < Vector3.Distance(target.position, transform.position)), gameObject);
}
2020-03-11 21:11:27 +01:00
}
2020-03-18 02:00:18 +01:00
}