Calculating angle and direction between two vectors



Normally, if we were to find the angle between two vectors, say up-vector and dir-vector, what we would do is to do a dot product between them. Since

a \cdot b = |a||b| \cos{\theta} and

\cos{\theta} = \frac{a \cdot b}{|a||b|}

dot_product_01However, since the calculated angle is the smallest / nearest angle between the two vectors, we can’t derive the (rotational) direction of one vector from the other. Thus in the following figure, it’s hard to figure out whether the direction vector is on the left or right of the up vector. The angle between two vectors calculated using dot product is always between 0° to 180°, thus we are not able to derive the direction from it.

dot_product_02One way to solve this issue is to take advantage of cosine behavior, where cosine of angles between 0° to 90° degrees are positive.MSP10011hcc64545g1h4fd500004dg5cdb243hc1f60

By introducing an extra ‘right’ vector which is right angle from the up-vector, we could further calculate the dot product between right vector and dir vector to check if the cosine of angle between them is positive or negative, and from it we could derive the rotational direction of the vector.



Programmatically, it could be coded as:

double calculateAngle( vec dir_vec, vec up_vec ) {

    vec right_vec = vec( -up_vec.y, up_vec.x );




    float dot_product = dir_vec );

    float angle = rad2deg( acos( dot_product ) );

    float dot_product_right = dir_vec );

    if( dot_product_right < 0.0 )

        angle = -angle;

    return angle;





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s