- Home /
2 Objects Moving in the Same Direction, which is in front and behind?
From the Unity documentation, I've been using the Dot product wrongly to find whether something is in front of the other. Previously, I was using it if > 0 is in front, < 0 is behind. Obviously, that's not the case all the time.
When I have 2 objects moving in the same direction, and according to the diagram below I referenced from another website, how do we find out if A is behind B when the both dot product is > 0?
Thanks!
Answer by Namey5 · Mar 26, 2021 at 05:10 AM
Well, that all depends on what you classify as being "in front" - if both objects truly are moving in the same direction (and you have that direction readily available as a vector; let's call it 'forwardDir') then all you need to do to determine the order of the objects is to take the dot product between 'forwardDir' and the vector from one object to the other;
// For simplicity, let's just assume 'forward' means along the z-axis;
Vector3 forwardDir = Vector3.forward;
// Then, find the vector going from objectA to objectB;
Vector3 delta = objectB.position - objectA.position;
// objectB will be in front if the dot product is greater than 0.
// If the dot product is equal to 0, then both objects are equal and you can just pick one (in this case we will default to objectA).
bool objectBIsInFront = Vector3.Dot (forwardDir, delta) > 0;
Your answer
Follow this Question
Related Questions
Incorrect usage of Vector3.Dot? 0 Answers
Direction between two point - add unit distance to player 0 Answers
Get Direction from 2 Vectors - and Apply to Transform 0 Answers
How to calculate order of directions relative to world forward around point? 1 Answer
Obtain direction from a point relative to another point 3 Answers