Reputation: 2083
Is there a way I can calculate the actual angle between two 3D Vectors in Unity? Vector3.Angle gives the shortest angle between the two vectors. I want to know the actual angle calculated in clockwise fashion.
Upvotes: 13
Views: 43997
Reputation: 393
It's easy if you just use addition and subtraction. Look at this:
/Degrees
float signedAngleBetween (Vector3 a, Vector3 b, bool clockwise) {
float angle = Vector3.angle(a, b);
//clockwise
if( Mathf.Sign(angle) == -1 && clockwise )
angle = 360 + angle;
//counter clockwise
else if( Mathf.Sign(angle) == 1 && !clockwise)
angle = - angle;
return angle;
}
Here's what i mean: if we are clockwise and the angle is negative, e.g. -170 to make it 180, you use this equation. "180-|angle|+180" you already know that the angle is negative, so, use "180-(-angle)+180" and add the 180's "360 + angle". Then if it's clockwise, CONTINUE but if it's counter clockwise, make the angle negative, this is because the other part of the 360 angle (which is the compliment of 360 + angle) is "360 - (360 + angle)" or "360 - 360 - angle" OR "(360 - 360) - angle" and, again, OR "- angle". So there we go... your finished angle.
Upvotes: 0
Reputation: 4056
This should be what you need. a
and b
are the vectors for which you want to calculate an angle, n
would be the normal of your plane to determine what you would call "clockwise/counterclockwise"
float SignedAngleBetween(Vector3 a, Vector3 b, Vector3 n){
// angle in [0,180]
float angle = Vector3.Angle(a,b);
float sign = Mathf.Sign(Vector3.Dot(n,Vector3.Cross(a,b)));
// angle in [-179,180]
float signed_angle = angle * sign;
// angle in [0,360] (not used but included here for completeness)
//float angle360 = (signed_angle + 180) % 360;
return signed_angle;
}
For simplicity I reuse Vector3.Angle
and then calculate the sign from the magnitude of the angle between plane normal n
and the cross product (perpendicular vector) of a
and b
.
Upvotes: 22
Reputation: 499
Try to use Vector3.Angle(targetDir, forward);
Since you want the shortest angle between them, then if the value returned is more than 180 degrees, just subtract 360 degrees with this value.
Check out http://answers.unity3d.com/questions/317648/angle-between-two-vectors.html
Upvotes: -8