# Getting the angle between 2 objects

Hello there, I’m having some difficulty to get the angle between two objects and know if the target object is it at my right or my left…
If I use this, (the code down here) I can get an angle difference, but only in 180 degrees…

``````		var relativePos = nextPoint - transform.position;
rotation = Quaternion.LookRotation(relativePos);

var forward = transform.forward;
var angle = Vector3.Angle(relativePos, forward);

//angle and Quaternion.Angle(transform.rotation, rotation) brings me the same result. but still I can't see witch side the object are...
``````

Hope anyone can help.
THANKS!

The trick is to check the cross product between the 2 vectors. In your case forward and relativePos (which isn’t actually a position but a direction ). The cross product of two vectors are a new vector perpendicular to the plane defined by the vectors, so now you just need to check if the y component of the cross product is positive or negative (I.e. is the vector pointing up or down). Up = nextPoint is on the right, Down = to the left (See code snippet)

BTW: Obviously I don’t know what your doing, but if the `rotation = Quaternion.LookRotation(relativePos)` line is actually `transform.rotation = Quaternion.LookRotation(relativePos)` I suggest that you move it after the rest of the code, otherwise the angle between the 2 object are always going to be 0 (since you’ve just rotate to face the other object directly).

``````var relativePos = nextPoint - transform.position;

var forward = transform.forward;
var angle = Vector3.Angle(relativePos, forward);
if (Vector3.Cross(forward, relativePos).y < 0) {
//Do left stuff
}
else {
//Do right stuff
}

rotation = Quaternion.LookRotation(relativePos);
``````
3 Likes

I worked Talzor!!!
I Thank you very much!!!
I owe you one! :lol:

I prefer:
var something : Transform; // position of the other object

var p : Vector3 = transform.InverseTransformPoint(something.position);

Now p is the position of something in my local coordinate space. If p.y > 0, it’s above me. If p.x < 0 it’s to my left. If p.z < 0 it’s behind me. Very convenient for writing any kind of AI code.

5 Likes

@Talzor : thanks a lot your code works like charm …