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.
To find the angle between two vectors a and b, we can use the dot product formula: a · b = |a| |b| cos θ. If we solve this for θ, we get θ = cos-1 [ (a · b) / (|a| |b|) ].
Vector 3 is a struct https://docs.unity3d.com/ScriptReference/Vector3.html and is commonly used to reference the X, Y, and Z position of an object. It can also be used for detecting direction and also used with rotations as well.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With