- Home /
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 :)
Yeah that's sure but what would be in that script? :D
In that script you can calculate the distance of enemy from player using Vector3.Distance() function. If that distance is less than your proposed distance. move the enemy in backward direction.
Answer by mmciver · Feb 27, 2017 at 04:16 PM
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;
navMeshAgent.Resume();
}
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 https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html, and if it's not using https://docs.unity3d.com/530/Documentation/ScriptReference/NavMeshAgent.FindClosestEdge.html to get the next best spot.
Thank you @mmciver, it a really simple and effective solution and works fine.
Your answer
Follow this Question
Related Questions
Get NavMeshAgent to look where it's going 0 Answers
Nav mesh agent position 1 Answer
NavMeshPath.corners.length is always 0 1 Answer
NavMeshAgent occasionally makes stale paths 0 Answers
NavMesh issue with spawning players 3 Answers