I have an enemy that wants to keep it’s distance from the player so whenever they get too close, the enemy picks a position a set distance behind them, checks if there’s a viable path and sets it as a new destination for the NavAgent.
public void Retreat()
{
//If the skeleton is already far enough from the player when this is called (from taking a hit), ignore it
float DistanceBetweenTarget = Vector3.Distance(transform.position, PlayerTarget.position);
if(DistanceBetweenTarget > MaxDistance)
{
return;
}
//Debug.Log("I gotta get outta here!");
Vector3 RetreatDirection = transform.forward * -1 * RetreatDistance;
Vector3 FirstDestination = transform.position + RetreatDirection;
SetPath(FirstDestination);
}
private void SetPath(Vector3 Destination)
{
//Check if the destination is on the navmesh
NavMeshHit Hit;
bool NavMeshFound = NavMesh.SamplePosition(Destination, out Hit, 1.0f, NavMesh.AllAreas);
if (NavMeshFound == true)
{
//Check if there's a viable path
NavMeshPath Path = new NavMeshPath();
NavAgent.CalculatePath(Hit.position, Path);
if (Path.status != NavMeshPathStatus.PathInvalid)
{
NavAgent.SetDestination(Hit.position);
Moving = true;
}
}
}
This is of course pretty basic and there are plenty of situations where it gives up on running away because its back is facing a wall or it’s on an elevated platform and isn’t considering jumping down. I’m not sure how to handle this because I usually know the destination in advance, is there any good videos on pathfinding that cover this situation?.