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.
I tried getting angle like this but not getting result I expected:
var angle = Vector3.Angle(objectB.forward, objectA.position - objectB.position);
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.
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.
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.