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

1 Answer 1

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\$
1
  • \$\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\$ Commented Jul 21, 2019 at 5:49

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.