# How can you tell if a gameobject is looking directly at another gameobject?

I’m using a coroutine to make a troop look at the enemy troop when it is within a radius, I want the troop to look at the gameobject. Is there a way to tell if the gameobject is looking directly at the other gameobject so I can stop the current coroutine and move to the next coroutine?

``````public IEnumerator LookAtEnemy()
{

Debug.Log ("Started");

yield return new WaitForSeconds (1);

//while (//Repeat until the object is staring at the object...) {

if (this.gameObject.CompareTag ("ShootingFriendly") && SightS.EnemiesInRange.Count > 0) {
{
Debug.Log ("Turning");
GameObject CurrentEnemy = SightS.EnemiesInRange [0].gameObject;
Quaternion Rot1 = Quaternion.LookRotation (CurrentEnemy.transform.position - this.gameObject.transform.position);
this.gameObject.transform.rotation = Quaternion.Slerp (this.gameObject.transform.rotation, Rot1, Time.deltaTime * 3);

Quaternion Rot = Quaternion.LookRotation (CurrentEnemy.transform.position - Gun.transform.position);
Gun.transform.rotation = Quaternion.Slerp (Gun.transform.rotation, Rot, Time.deltaTime * 3);
}

//}

}

}
``````

Since you have already the target rotation as quaternion you can simply take the angle between them and test if it’s blow some threshold.

``````if (Quaternion.Angle(Gun.transform.rotation, Rot) < 5f)
{
// gun almost looks at the target
}
``````

You can make the threshold smaller, but keep in mind it might take quite a bit longer. Mathematically you will never directly look at the target since you always only rotate a fraction of the remaining difference. You will get closer and closer but it takes longer and longer. Due to floating point precision limitations you might actually reach the target but it can take a very long time. For most applications a small threshold would be enough.

If you want it more precise you shouldn’t use Slerp with Time.deltaTime. You could use RotateTowards or similar methods.