How to check if object A is in front of object B

I have an object B I can place in all 4 directions (north, eat, south, west). I need some logic to check if object A is in front of object B.

Orange box is Object B, red/blue marks are object A. All red marks should return true, all blue marks should return false. I tried to calculate the angle in front of the object but Im not having any success.

8915392--1221022--upload_2023-3-30_16-36-54.png

I tried getting angle like this but not getting result I expected:

var angle = Vector3.Angle(objectB.forward, objectA.position - objectB.position);

Is this possible?

Looks correct to me. Some people mess up the order of subtraction but you have it correct – it should be the new object minus the one to be in front of; that gives an arrow pointing from orange B to red A. Angle compares the 2 arrows and gives a 0-180 result. It can’t tell if you’re to the right or left (or above or below), but for “in front” checking angle<90 works great.

1 Like

Hmm okay, Im getting the “wrong” angle when im printing it, strange.

I would expect to get 0-180 in front, 181-360 behind. The results are not close to that at all, and vary a lot depending on the rotation of Object B.

I thought you could use Vector3.Dot to figure if an object is front or behind?

No, 0Âş is where the B.forward is pointing directly at A; 90Âş is where B.forward is perpendicular to the direction of A in either direction; 180Âş is where B.forward points directly away from A.

There is also Vector3.SignedAngle(), which would give a positive or negative value depending on whether B.forward misses the A in the clockwise or counterclockwise direction, as seen from an “above” vantage point you supply.

Yes, the Vector3.Angle formula can be implemented using Vector3.Dot, Vector3.Normalize, and Mathf.Acos. Used alone, Vector3.Dot can definitely tell whether you’re in the forward-facing half of the range or not.

I would normalize both vectors (the forward one should already be normalized) and then check if the dot product is larger than 0.1 or something.

Could also get the InverseTransformPoint and check the Z-axis, depending on what other information you need to know.

Edit: to clarify, incase you also wanted to know if something was above/below, and/or to the left/right of your character you could check the other axis as well.

I ended up using Vector.Dot, thank you!