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

59 lines
2.0 KiB
C#
Raw 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-14 18:05:41 +02:00
private Enemy Enemy;
2019-08-14 21:31:58 +02:00
private Vector2 TargetDirection;
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-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-14 18:05:41 +02:00
Vector2 position = Enemy.transform.position;
2019-08-14 21:31:58 +02:00
Vector2 delta = (Vector2)Target.position - position;
2019-08-03 17:36:17 +02:00
if (delta.magnitude > CloseEnoughRadius) {
2019-08-14 21:31:58 +02:00
Enemy.StartMovingTo(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
}
}
}
}
}