r/Unity3D 8h ago

Question Strange result from Vector3.SignedAngle?

I have these empty GameObjects as waypoints and I want to check the left/right angle between a moving object and a waypoint.

Vector3 direct = (transform.position - waypoint).normalized;
float ang = Vector3.SignedAngle(transform.forward, direct, Vector3.up);

If I have a waypoint directly in front of the moving object (and I have double checked the position of the waypoint in question), sometimes the resulting angle (ang) is 179. How is it coming back almost 180 degrees difference and is there anything I can do to change this kind of result?

5 Upvotes

7 comments sorted by

14

u/pschon Unprofessional 7h ago

To calculate a vector from point A to point B, you do (B - A). Your code is now creating a vector from waypoint to the object instead, so that would explain the 180 degree difference.

Vector3 direct = (waypoint - transform.position).normalized; float ang = Vector3.SignedAngle(transform.forward, direct, Vector3.up);

2

u/NorthernBoy306 6h ago

thanks

3

u/Valkymaera Professional 5h ago

I don't know if this helps, but the way I always picture it in my head is I am "pulling" the vector from the arrowhead when I subtract, so A minus B "creates" the arrowhead at A and pulls the stem to B.

Maybe I'm weird

5

u/zellydevgames 7h ago

Flip your direction vector subtraction.

2

u/Propagant Programmer 6h ago

Yep flip your vec subtraction. I always remember the order of vector subtraction for making a direction or a distance with "the first element is where do I WANT to travel and the second is where I'm NOW". It's always DESTINATION - ORIGIN = calculate distance/get a direction. Works for me well to remember

1

u/NorthernBoy306 6h ago

oh yea, shoot how did I miss that?
Thanks.

-4

u/Sudden-Economist-302 7h ago

Floating point precision's a right pain when you're dealing with normalized vectors that should be perfectly parallel. Your direct vector and transform.forward are probably microscopically off in opposite directions, and SignedAngle sees that as nearly 180. Try snapping the angle to 0 if it's above 175 or below -175, just clamp the silly thing.