# Unity3d: Find which gameObject is in front

I have two gameObjects A and B. They are rotated at 90 degrees, which makes its local y axis face forward.

1st Case

In this case, the local y position of B is ahead of local y position of A

2nd Case

Even though their global position is same as the 1st case, we can observe here that local y position of A is ahead of local y position of B.

I tried using A.transform.localPosition.y and B.transform.localPosition.y to find which is greater but it doesnt work. What can I do to find which is front in these two different cases?

• What are you after exaclty? In front, but with regards to what? – Vaillancourt Jul 20 '19 at 23:09
• @AlexandreVaillancourt It's based on perspective and direction – MrRobot9 Jul 20 '19 at 23:13
• @AlexandreVaillancourt In 1st case, Imagine they are running straight, and in 2nd case, they are running at the left direction. The global postions are same in borh cases, but in 1st case B is ahead and in 2nd case, A is ahead – MrRobot9 Jul 20 '19 at 23:15
• Yes, and so you want to find out which one is ahead of the other, assuming they'll always be facing the same direction and turning at the same time? – Vaillancourt Jul 20 '19 at 23:34
• Yeah exactly!!! – MrRobot9 Jul 20 '19 at 23:36

You can check simple ahead/behind relationships using the dot product:

Vector3 displacement = B.transform.position - A.transform.position;

float dot = Vector3.Dot(displacement, A.transform.forward);


If dot is greater than zero, then B is ahead of A along A's forward vector. (The arrow from A to B has a component in the same direction as A's forward)

If dot is less than zero, then B is behind A along A's forward vector. (The arrow from A to B has a component in the opposite direction as A's forward)

If dot is zero, then B is somewhere directly to the side of A, neither in front nor behind. The A→B arrow points perpendicular to A's forward axis.

• FWIW, this approach will work even if B is in a different orientation from A -- it will just tell you whether B is in front or behind A, relative to A's orientation. N.B. that if the two orientations are different, then it is possible for A to be ahead of B along A's path, and B to be simultaneously ahead of A on B's path. – A C Jul 21 '19 at 5:49