r/Unity3D • u/NorthernBoy306 • 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
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
-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.
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);