Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating actual angle between two vectors in Unity3D

Tags:

vector

unity3d

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.

like image 473
shaveenk Avatar asked Oct 30 '13 06:10

shaveenk


People also ask

How do you find the exact angle between two vectors?

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|) ].

What is Vector3 in Unity C#?

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.


1 Answers

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.

like image 118
Jerdak Avatar answered Oct 11 '22 04:10

Jerdak