How to Check if a Three.js Object Faces the Camera

In Three.js, determining whether a 3D object is facing the camera is a common task for optimizing rendering, implementing billboarding, or triggering interaction events. This article explains how to use the mathematical dot product on two THREE.Vector3 objects—the object’s forward direction and the vector pointing from the object to the camera—to quickly calculate and verify if the object is oriented toward the camera.

The Mathematics Behind the Solution

The dot product of two normalized vectors yields a value between -1 and 1. This value represents the cosine of the angle between them: * Greater than 0 (Positive): The vectors point in the same general direction (angle is less than 90 degrees), meaning the object is facing toward the camera. * Less than 0 (Negative): The vectors point in opposite directions (angle is greater than 90 degrees), meaning the object is facing away from the camera. * Equal to 0: The vectors are perpendicular (exactly 90 degrees apart).

Step-by-Step Implementation in Three.js

To perform this check, you need to calculate two normalized world-space vectors: the object’s forward direction and the direction vector from the object to the camera.

1. Retrieve World Positions and Directions

First, instantiate the helper vectors to avoid garbage collection overhead during animation loops, and extract the necessary world-space coordinates.

import * as THREE from 'three';

// Instantiate vectors once to reuse in your render loop
const cameraPosition = new THREE.Vector3();
const objectPosition = new THREE.Vector3();
const objectForward = new THREE.Vector3();
const toCameraDir = new THREE.Vector3();

// Update world matrices if calculations run before the renderer updates them automatically
camera.updateMatrixWorld();
myObject.updateMatrixWorld();

// Get the world positions of the camera and the object
camera.getWorldPosition(cameraPosition);
myObject.getWorldPosition(objectPosition);

2. Calculate the Vector to the Camera

Subtract the object’s position from the camera’s position to get the direction vector pointing from the object to the camera, then normalize it.

toCameraDir.subVectors(cameraPosition, objectPosition).normalize();

3. Get the Object’s Forward Direction

Use the getWorldDirection method on the object. In Three.js, this method returns a normalized vector representing the direction of the object’s local positive Z-axis in world space.

myObject.getWorldDirection(objectForward);

4. Calculate and Interpret the Dot Product

Use the .dot() method of THREE.Vector3 to calculate the dot product of the two vectors.

const dotProduct = objectForward.dot(toCameraDir);

if (dotProduct > 0) {
    console.log("The object is facing the camera.");
} else {
    console.log("The object is facing away from the camera.");
}