74 lines
2.9 KiB
C#
74 lines
2.9 KiB
C#
using Pathfinding;
|
|
using UnityEngine;
|
|
|
|
namespace Reset.Units{
|
|
public class EnemyPathfinding : MonoBehaviour, IUnitDirectionProvider{
|
|
public Vector2 Direction{ get; set; }
|
|
|
|
public Transform targetPosition;
|
|
|
|
private Seeker seeker;
|
|
|
|
public float nextWaypointDistance = 3;
|
|
private int currentWaypoint;
|
|
|
|
public Path path;
|
|
public bool reachedEndOfPath;
|
|
|
|
public void Start(){
|
|
seeker = GetComponent<Seeker>();
|
|
// If you are writing a 2D game you should remove this line
|
|
// and use the alternative way to move sugggested further below.
|
|
|
|
seeker.StartPath(transform.position, targetPosition.position, OnPathComplete);
|
|
}
|
|
|
|
public void OnPathComplete(Path p){
|
|
if (!p.error) {
|
|
path = p;
|
|
// Reset the waypoint counter so that we start to move towards the first point in the path
|
|
currentWaypoint = 0;
|
|
}
|
|
}
|
|
|
|
public void Update(){
|
|
if (path == null) {
|
|
// We have no path to follow yet, so don't do anything
|
|
return;
|
|
}
|
|
|
|
reachedEndOfPath = false;
|
|
// The distance to the next waypoint in the path
|
|
float distanceToWaypoint;
|
|
while (true) {
|
|
// If you want maximum performance you can check the squared distance instead to get rid of a
|
|
// square root calculation. But that is outside the scope of this tutorial.
|
|
distanceToWaypoint = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
|
|
if (distanceToWaypoint < nextWaypointDistance) {
|
|
// Check if there is another waypoint or if we have reached the end of the path
|
|
if (currentWaypoint + 1 < path.vectorPath.Count) {
|
|
currentWaypoint++;
|
|
} else {
|
|
// Set a status variable to indicate that the agent has reached the end of the path.
|
|
// You can use this to trigger some special code if your game requires that.
|
|
reachedEndOfPath = true;
|
|
break;
|
|
}
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Slow down smoothly upon approaching the end of the path
|
|
// This value will smoothly go from 1 to 0 as the agent approaches the last waypoint in the path.
|
|
var speedFactor = reachedEndOfPath ? Mathf.Sqrt(distanceToWaypoint / nextWaypointDistance) : 1f;
|
|
|
|
// Direction to the next waypoint
|
|
// Normalize it so that it has a length of 1 world unit
|
|
Vector3 dirToPoint = (path.vectorPath[currentWaypoint] - transform.position).normalized * speedFactor;
|
|
|
|
Direction = dirToPoint.ToVector2();
|
|
}
|
|
}
|
|
|
|
} |