# Calculating angle and direction between two vectors

Standard

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|}$ However, 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. One way to solve this issue is to take advantage of cosine behavior, where cosine of angles between 0° to 90° degrees are positive. 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 );

dir_vec.normalize();

up_vec.normalize();

right_vec.normalize();

float dot_product = up_vec.dot( dir_vec );

float angle = rad2deg( acos( dot_product ) );

float dot_product_right = right_vec.dot( dir_vec );

if( dot_product_right < 0.0 )

angle = -angle;

return angle;

}