How to Make Three.js Camera Look at a Vector3

In Three.js, keeping a camera pointed at a specific 3D coordinate is crucial for tracking moving objects, creating dynamic cutscenes, or focusing the user’s attention on a point of interest. This article provides a straightforward guide on how to use the built-in lookAt method and integrate it into your animation loop to ensure the camera consistently targets any Vector3 coordinate.

Using the lookAt Method

The simplest way to point a Three.js camera at a specific coordinate is by calling the lookAt method on your camera instance. This method takes a THREE.Vector3 object as an argument and automatically rotates the camera to face that position.

// Define the target coordinate
const targetPosition = new THREE.Vector3(0, 5, 0);

// Point the camera at the target
camera.lookAt(targetPosition);

Keeping the Focus in the Animation Loop

If either your camera or the target coordinate is moving, you must continuously update the camera’s orientation. To do this, place the lookAt method inside your requestAnimationFrame loop.

const targetPosition = new THREE.Vector3(0, 0, 0);

function animate() {
    requestAnimationFrame(animate);

    // Update target position here if it is moving
    // targetPosition.x += 0.01;

    // Force the camera to consistently look at the vector
    camera.lookAt(targetPosition);

    renderer.render(scene, camera);
}

animate();

Handling OrbitControls Conflict

If your project uses OrbitControls, calling camera.lookAt() directly will not work because the controls constantly overwrite the camera’s rotation. To make the camera look at a specific Vector3 while using OrbitControls, you must update the controls’ target instead.

// Set the target of the controls
controls.target.copy(targetPosition);

// You must call update after modifying the target
controls.update();

By updating the controls’ target inside your animation loop, the camera will consistently look at the specified Vector3 coordinate even while user interaction is enabled.