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

67 lines
2.2 KiB
C#
Raw Permalink Normal View History

2019-08-03 17:36:17 +02:00
using UnityEngine;
2019-08-14 16:17:48 +02:00
using Saltosion.OneWeapon.Enemies;
2019-08-03 17:36:17 +02:00
namespace Saltosion.OneWeapon.AI.Behaviours {
2019-08-14 18:05:41 +02:00
[RequireComponent(typeof(Enemy))]
2019-08-04 15:44:44 +02:00
public class Follow : AIBehaviour {
2019-08-03 17:36:17 +02:00
public Transform Target;
public float CloseEnoughRadius;
2019-08-04 17:35:24 +02:00
public float TargetPositionUpdateFrequency = 5f;
2019-08-18 20:32:07 +02:00
public Vector2 TargetDirection { private set; get; }
2019-08-14 18:05:41 +02:00
private Enemy Enemy;
2019-08-04 17:35:24 +02:00
private float TargetPositionUpdateCooldown;
2019-08-14 18:05:41 +02:00
private void Start() {
Enemy = GetComponent<Enemy>();
}
2019-08-04 17:35:24 +02:00
2019-08-14 18:05:41 +02:00
private void Update() {
2019-08-04 17:35:24 +02:00
if (Target != null && TargetPositionUpdateCooldown <= 0) {
TargetPositionUpdateCooldown = 1.0f / TargetPositionUpdateFrequency;
2019-08-14 21:31:58 +02:00
TargetDirection = Target.position - Enemy.transform.position;
2019-08-04 17:35:24 +02:00
} else if (Target == null) {
TargetPositionUpdateCooldown = 0.0f;
} else {
TargetPositionUpdateCooldown -= Time.deltaTime;
}
}
2019-08-03 17:36:17 +02:00
2019-08-14 21:31:58 +02:00
public void SetUpdateFrequency(float freq) {
TargetPositionUpdateFrequency = freq;
TargetPositionUpdateCooldown = Mathf.Min(TargetPositionUpdateCooldown, 1.0f / freq);
}
2019-08-18 20:32:07 +02:00
public float GetDistance() {
return Target == null ? -1.0f : (Target.position - Enemy.transform.position).magnitude;
}
2019-08-14 18:05:41 +02:00
public override bool CanBehave() {
2019-08-14 21:31:58 +02:00
bool TargetExists = Target != null;
if (!TargetExists) {
Enemy.StopMoving();
CurrentStatus = "NoTarget";
}
return TargetExists;
2019-08-03 17:36:17 +02:00
}
2019-08-14 18:05:41 +02:00
public override void Execute() {
2019-08-03 17:36:17 +02:00
if (Target != null) {
2019-08-18 20:32:07 +02:00
if (GetDistance() > CloseEnoughRadius) {
Enemy.StartMovingTo((Vector2)Enemy.transform.position + TargetDirection);
2019-08-14 18:05:41 +02:00
CurrentStatus = "Approach";
} else {
Enemy.StopMoving();
CurrentStatus = "CloseEnough";
2019-08-03 17:36:17 +02:00
}
}
}
2019-08-18 20:32:07 +02:00
private void OnDrawGizmosSelected() {
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, CloseEnoughRadius);
}
2019-08-03 17:36:17 +02:00
}
}