Calculate Angle Between Two Vectors in Three.js

This article explains how to calculate the angle between two 3D vectors in Three.js using the Vector3.angleTo() method. You will learn the syntax of the method, see a practical code example, and understand how to convert the resulting angle from radians to degrees for easier utilization in your 3D projects.

Understanding the angleTo Method

In Three.js, the THREE.Vector3 class provides a built-in method called angleTo(). This method calculates the angle between the current vector and a target vector.

The mathematical formula used under the hood is based on the dot product of the two vectors divided by the product of their magnitudes:

\[\theta = \arccos\left(\frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \|\mathbf{v}\|}\right)\]

Because Three.js handles this calculation internally, you do not need to manually normalize the vectors or calculate the dot product yourself. The angleTo() method always returns the shortest angle between the two vectors as a positive value in radians, ranging from \(0\) to \(\pi\) (0 to 180 degrees).

Code Example

Here is a straightforward example demonstrating how to define two vectors and compute the angle between them:

import * as THREE from 'three';

// 1. Define two Vector3 directions
const vectorA = new THREE.Vector3(1, 0, 0); // Pointing right (X-axis)
const vectorB = new THREE.Vector3(0, 1, 0); // Pointing up (Y-axis)

// 2. Compute the angle in radians
const angleInRadians = vectorA.angleTo(vectorB);

// 3. Convert the angle to degrees (optional)
const angleInDegrees = THREE.MathUtils.radToDeg(angleInRadians);

console.log(`Angle in Radians: ${angleInRadians}`); // Output: 1.5707963267948966 (π / 2)
console.log(`Angle in Degrees: ${angleInDegrees}`); // Output: 90

Key Considerations