BloodAndGore/Assets/Scripts/AI/Behaviours/Follow.cs
2019-08-18 21:32:07 +03:00

67 lines
2.2 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;
public Vector2 TargetDirection { private set; get; }
private Enemy Enemy;
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 float GetDistance() {
return Target == null ? -1.0f : (Target.position - Enemy.transform.position).magnitude;
}
public override bool CanBehave() {
bool TargetExists = Target != null;
if (!TargetExists) {
Enemy.StopMoving();
CurrentStatus = "NoTarget";
}
return TargetExists;
}
public override void Execute() {
if (Target != null) {
if (GetDistance() > CloseEnoughRadius) {
Enemy.StartMovingTo((Vector2)Enemy.transform.position + TargetDirection);
CurrentStatus = "Approach";
} else {
Enemy.StopMoving();
CurrentStatus = "CloseEnough";
}
}
}
private void OnDrawGizmosSelected() {
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, CloseEnoughRadius);
}
}
}