0
\$\begingroup\$

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

1st Case

enter image description here

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

2nd Case

enter image description here

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?

\$\endgroup\$
  • \$\begingroup\$ What are you after exaclty? In front, but with regards to what? \$\endgroup\$ – Vaillancourt Jul 20 '19 at 23:09
  • 1
    \$\begingroup\$ @AlexandreVaillancourt It's based on perspective and direction \$\endgroup\$ – MrRobot9 Jul 20 '19 at 23:13
  • 1
    \$\begingroup\$ @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 \$\endgroup\$ – MrRobot9 Jul 20 '19 at 23:15
  • \$\begingroup\$ 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? \$\endgroup\$ – Vaillancourt Jul 20 '19 at 23:34
  • \$\begingroup\$ Yeah exactly!!! \$\endgroup\$ – MrRobot9 Jul 20 '19 at 23:36
5
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – A C Jul 21 '19 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.