Navmesh Agent "move back" when player comes to close?

Hey there,
my navmesh agents are working pretty good all the time. Problem is that my agents are not meele and the player can come to close to the enemies.

So the agents got an auto stopping distance (like 8 units) but the player can come closer for sure. When the player gets to close (like 2-3 units) i want the enemys to move back because it would be much more realistic.

How would you do that?

Greets :slight_smile:

Something like…

Vector3 toPlayer = player.transform.position - transform.position;
if (Vector3.Distance(player.transform.position - transform.position) < 3) {
  Vector3 targetPosition = toPlayer.normalized * -3f;
  navMeshAgent.destination = targetPosition;

This just gets a point 3 units backwards away from the player, sets the destination to that, and then tells the agent to go there.

You would really need to do more work however, for example checking to see if it’s a valid location via Unity - Scripting API: AI.NavMesh.SamplePosition, and if it’s not using Unity - Scripting API: NavMeshAgent.FindClosestEdge to get the next best spot.