Detect if a position is in front, to the left or right of a transform.

Hi, I have 2 objects of which both objects need to know if they are in in front or behind each other and if they are to the left or right from each other. So I need to know the name of a function that can help me to see if a world position vector is in front,behind,left || right relative to a local transform.

I know something like this is probably in there but I don’t know how it’s called.

And it would also be nice if I could calculate the length of how far one object is in front of another. So I am not looking for the squared distance but just the distance on it’s local axis.

As far as I know there isn’t a single function for that. But you can get the forward, backward, left and right vectors of the transforms (built in properties).

I’ll just use forward as an example:

bool FrontTest(Transform otherTransform)
{
Vector3 fwd = transform.forward;
Vector3 vec = otherTransform.position - transform.position;
vec.Normalize()

float ang = Mathf.Acos(Vector3.Dot(fwd, vec)) * Mathf.Rad2Deg;

bool isFront = false;

if (ang <= 45.0f)
  return true;

return false;
}

This is completely untested code, so there may be some syntax errors, but the logic should be sound. If you’d like me to explain what’s happening I’ll be glad to.

Hope this helps.

Another approach would be to transform the target point into local space using Transform.InverseTransformPoint(). You can then derive the information you need directly from the coordinates of the transformed point. (For example, the sign of z will tell you if the point is in front or behind, and the sign of x will tell you if the point is to the left or right.)

1 Like

Does this accomplish the same thing as Vector3.Angle() ?

[/quote]

The docs for Vector3.Angle() don’t mention a unit-length requirement, so I suspect it’s implemented differently than the above code. (Specifically, it probably divides through by the product of the lengths of the vectors, or uses the ‘atan2’ method of computing the angle.)

@Wahooney: Note that with this approach you’ll want to clamp the input to acos() to the range [-1, 1] to correct for numerical error.