Stop NPC x distance away from Player ?

Okay, so this is what i need to solve …

The NPC patrols around, when it sees the Player,

  1. it moves towards it, but stops a certain units away from Player, and attacks,
  2. if the Player moves again, it does 1 again…

the problem i am having is: using Vector3.Distance, i do get the NPC to stop but, it seems - depending on the Angle (!?) of the Player, the NPC stops at varying distance (either touching close or a bit far) at times. IDK why it’s happening though.

Please look at the pictures to understand what i mean…

Image 1:
http://postimg.org/image/m5dm1ofep/
Image 2:
http://postimg.org/image/cyvbeea69/

Thanks

If you are using a NavMeshAgent for your NPCs, you could simply use the stoppingDistance attribute directly from the inspector.

alt text

If you are doing the movement of your NPCs all by yourself, provide some code to see where is the problem.

Thank you everyone … I’m unsure if this really means anything to you guys but this is the part of the code i’m having problem with… (the full code is basically navmeshagent initialization, error checks, followed by ontriggerstay and broken up ‘enemysight’ code of the Stealth project)

if (Vector3.Distance (transform.position, SceneNavigationDetails.Player.position) <= distance.normalAttack)
			{
				navMeshAgent.Stop ();
				transform.rotation = Quaternion.LookRotation (SceneNavigationDetails.Player.position - transform.position);
			}
			else
			{
				navMeshAgent.Resume ();
				navMeshAgent.SetDestination (SceneNavigationDetails.lastPlayerSightingPosition);
			}

The SceneNavigationDetails is a static class which is initialized by GameManager script, i looked at the Stealth EnemySight and modified it to suit my needs…

distance.normalAttack is 2.5f, but it seems the stoppingDistance is unsuitable with the current code i have (doesn’t go along with it)

I use the NavMeshAgent, and it’s SetDestination …

Thank you…