# Detect player in range of enemy...

How can I detect if the player is within a certain range of an enemy and only then start tracking the player.

Related question: Efficient spatial searching (finding game objects within a certain range)

Jester answer explains things quite well. The only thing his solution doesn't take into account is the case where some obstacle is between the player and the enemy, that obstacle blocking the enemies view towards the player. I add here an example code from that is an implementation of jester's solution plus the idea I suggested above.

``````//if an enemy as further than maxDistance from you, it cannot see you
var maxDistanceSquared = maxDistance * maxDistance;
var rayDirection : Vector3 = playerObject.transform.localPosition - transform.localPosition;
var enemyDirection : Vector3 = transform.TransformDirection(Vector3.forward);
var angleDot = Vector3.Dot(rayDirection, enemyDirection);
var playerInFrontOfEnemy = angleDot > 0.0;
var playerCloseToEnemy =  rayDirection.sqrMagnitude < maxDistanceSquared;

if ( playerInFrontOfEnemy && playerCloseToEnemy)
{
//by using a Raycast you make sure an enemy does not see you
//if there is a bulduing separating you from his view, for example
//the enemy only sees you if it has you in open view
var hit : RaycastHit;
if (Physics.Raycast (transform.position,rayDirection, hit, maxDistance)
&& hit.collider.gameObject==playerObject) //player object here will be your Player GameObject
{
//enemy sees you - perform some action
}
else
{
//enemy doesn't see you
}
}

``````

This code should be added in the Update function of your EnemyAI script. This script will be attached to everyone of your enemies.

you can subtract the world position of the player from the world position of the enemy to get a distance vector between the player and that enemy. you can then check the length of that distance vector with the "magnitude" member variable of the Vector3 class. if the length of the vector is less than a certain threshold, the player is within range of that enemy.

if you're not concerned with line of sight, that should work fine. you could also check the angle between that distance vector against the current forward vector of the enemy and see if the player could be seen by that enemy or if the player is behind or too far to the side to be seen.

This has been asked before. Look for other questions tagged proximity.

sorry admin, I want to ask whether in this script range must use AI NavMeshAgent?