BloodAndGore/Assets/Scripts/AI/Behaviours/Follow.cs

53 lines
1.7 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 TargetPosition;
private float TargetPositionUpdateCooldown;
private void Start() {
Enemy = GetComponent<Enemy>();
}
private void Update() {
if (Target != null && TargetPositionUpdateCooldown <= 0) {
TargetPositionUpdateCooldown = 1.0f / TargetPositionUpdateFrequency;
TargetPosition = Target.position;
} else if (Target == null) {
TargetPositionUpdateCooldown = 0.0f;
} else {
TargetPositionUpdateCooldown -= Time.deltaTime;
}
}
public override bool CanBehave() {
return Target != null;
}
public override void Execute() {
if (Target != null) {
Vector2 position = Enemy.transform.position;
Vector2 delta = TargetPosition - position;
if (delta.magnitude > CloseEnoughRadius) {
delta -= delta.normalized * CloseEnoughRadius;
Enemy.StartMovingTo(position + delta);
CurrentStatus = "Approach";
} else {
Enemy.StopMoving();
CurrentStatus = "CloseEnough";
}
} else {
Enemy.StopMoving();
CurrentStatus = "NoTarget";
}
}
}
}