Monday, May 30, 2016

2d - How do I use the dot product to get an angle between two vectors?


I am learning to use normalized vectors in my games.



I've learned that in order to know the angle between two vectors, I can use the dot product. This gives me a value between -1 and 1, where



  • 1 means the vectors are parallel and facing the same direction (the angle is 180 degrees).

  • -1 means they are parallel and facing opposite directions (still 180 degrees).

  • 0 means the angle between them is 90 degrees.


I want to know how to convert the dot product of two vectors, to an actual angle in degrees. For example, if the dot product of two vectors is 0.28, what is the corresponding angle, between 0 and 360 degrees?



Answer



dot(A,B) = |A| * |B| * cos(angle)
which can be rearranged to

angle = arccos(dot(A,B) / (|A|* |B|)).


With this formula, you can find the smallest angle between the two vectors, which will be between 0 and 180 degrees. If you need it between 0 and 360 degrees this question may help you.




By the way, the angle between two parallel vectors pointing in the same direction should be 0 degrees, not 180.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...