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

53 lines
1.7 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-04 17:35:24 +02:00
private Vector2 TargetPosition;
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;
TargetPosition = Target.position;
} else if (Target == null) {
TargetPositionUpdateCooldown = 0.0f;
} else {
TargetPositionUpdateCooldown -= Time.deltaTime;
}
}
2019-08-03 17:36:17 +02:00
2019-08-14 18:05:41 +02:00
public override bool CanBehave() {
2019-08-04 17:35:24 +02:00
return Target != null;
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-04 17:35:24 +02:00
Vector2 delta = TargetPosition - position;
2019-08-03 17:36:17 +02:00
if (delta.magnitude > CloseEnoughRadius) {
delta -= delta.normalized * CloseEnoughRadius;
2019-08-14 18:05:41 +02:00
Enemy.StartMovingTo(position + delta);
CurrentStatus = "Approach";
} else {
Enemy.StopMoving();
CurrentStatus = "CloseEnough";
2019-08-03 17:36:17 +02:00
}
2019-08-14 18:05:41 +02:00
} else {
Enemy.StopMoving();
CurrentStatus = "NoTarget";
2019-08-03 17:36:17 +02:00
}
}
}
}