59 lines
2.0 KiB
C#
59 lines
2.0 KiB
C#
using UnityEngine;
|
|
using Saltosion.OneWeapon.Enemies;
|
|
|
|
namespace Saltosion.OneWeapon.AI.Behaviours {
|
|
[RequireComponent(typeof(Enemy))]
|
|
public class Follow : AIBehaviour {
|
|
public Transform Target;
|
|
public float CloseEnoughRadius;
|
|
public float TargetPositionUpdateFrequency = 5f;
|
|
|
|
private Enemy Enemy;
|
|
private Vector2 TargetDirection;
|
|
private float TargetPositionUpdateCooldown;
|
|
|
|
private void Start() {
|
|
Enemy = GetComponent<Enemy>();
|
|
}
|
|
|
|
private void Update() {
|
|
if (Target != null && TargetPositionUpdateCooldown <= 0) {
|
|
TargetPositionUpdateCooldown = 1.0f / TargetPositionUpdateFrequency;
|
|
TargetDirection = Target.position - Enemy.transform.position;
|
|
} else if (Target == null) {
|
|
TargetPositionUpdateCooldown = 0.0f;
|
|
} else {
|
|
TargetPositionUpdateCooldown -= Time.deltaTime;
|
|
}
|
|
}
|
|
|
|
public void SetUpdateFrequency(float freq) {
|
|
TargetPositionUpdateFrequency = freq;
|
|
TargetPositionUpdateCooldown = Mathf.Min(TargetPositionUpdateCooldown, 1.0f / freq);
|
|
}
|
|
|
|
public override bool CanBehave() {
|
|
bool TargetExists = Target != null;
|
|
if (!TargetExists) {
|
|
Enemy.StopMoving();
|
|
CurrentStatus = "NoTarget";
|
|
}
|
|
return TargetExists;
|
|
}
|
|
|
|
public override void Execute() {
|
|
if (Target != null) {
|
|
Vector2 position = Enemy.transform.position;
|
|
Vector2 delta = (Vector2)Target.position - position;
|
|
if (delta.magnitude > CloseEnoughRadius) {
|
|
Enemy.StartMovingTo(position + TargetDirection);
|
|
CurrentStatus = "Approach";
|
|
} else {
|
|
Enemy.StopMoving();
|
|
CurrentStatus = "CloseEnough";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|