Getting the angle between two 3D vectors

Getting the angle between two 3D vectors

onedayitwillmake No Comment
math snippet

Another short post related to a question I was asked, that I figure might be helpful to others.
Getting the angle between two vectors in 2D is as simple as:

var angle = Math.atan2(vectorA.y - vectorB.y, vectorA.x - vectorB.x)

However that does not work in 3D space, however the angle between any two vectors (2D or 3D) is defined as the

cosine theta = (A dot B) / Normalized-A * Normalized-B

Where theta is the angle between them. To find theta, we can inverse the equation:

theta = acos( (A dot B) / Normalized-A * Normalized-B )

In code getting the angle between two vectors in 3D space translates to:

// Make up two vectors
var vectorA = new Vector3(5, -20, -14);
var vectorB = new Vector3(-1, 3, 2);
 
// Store some information about them for below
var dot = vectorA.dot(vectorB);
var lengthA = vectorA.length();
var lengthB = vectorB.length();
 
// Now to find the angle
var theta = Math.acos( dot / (lengthA * lengthB) ); // Theta = 3.06 radians or 175.87 degrees

Leave a Reply


*