Using atan2 to find angle between two vectors

user3150201 picture user3150201 · Jan 31, 2014 · Viewed 107.8k times · Source

I understand that:

atan2(vector.y, vector.x) = the angle between the vector and the X axis.

But I wanted to know how to get the angle between two vectors using atan2. So I came across this solution:

atan2(vector1.y - vector2.y, vector1.x - vector2.x)

My question is very simple:

Will the two following formulas produce the same number?

  • atan2(vector1.y - vector2.y, vector1.x - vector2.x)

  • atan2(vector2.y - vector1.y, vector2.x - vector1.x)

If not: How do I know what vector comes first in the subtractions?

Answer

Martin R picture Martin R · Jan 31, 2014
 atan2(vector1.y - vector2.y, vector1.x - vector2.x)

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);

and you may want to normalize it to the range [0, 2 π):

if (angle < 0) { angle += 2 * M_PI; }

or to the range (-π, π]:

if (angle > M_PI)        { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }