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?
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;