Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Camera Controls in Three.js

So far the camera has stood where your code put it. In this part you hand it over: drag to orbit a scene, scroll to zoom, and then write a camera that chases a moving player the way a drone follows a car.

Part 9 of 12 ~15 min JavaScript
Part 9 of 12

What you'll learn

  • What a three.js addon is, and how one extra import line brings in OrbitControls, the most-used tool that is not in the core library.
  • How OrbitControls lets a person orbit, zoom, and pan the camera with a mouse or a finger, and the handful of settings that shape it: target, damping, distance limits, the floor lock, pan, and auto-rotate.
  • Why controls.update() has to run every frame, and the one case where you must not run it.
  • How to write a follow camera with lerp and lookAt that glides behind a moving player at the same speed on every device.

The Big Idea

Who is holding the camera?

In every part so far, the camera has been a tripod. Part 1 set camera.position.z = 5 and left it there; Part 2 moved it with sliders, but that was still your code deciding where it stood. Real 3D apps are different. Open a product page with a 3D sneaker and you spin it with your finger. Open a game and the camera rides behind your character, swinging around corners a beat after you do. Somebody is holding the camera, and that somebody is either the user or the game. This page teaches both grips.

The first is user-driven. The person looking at the scene drags to circle around it, scrolls to move closer or farther, and maybe right-drags to slide sideways. Every 3D viewer you have used works this way, and three.js ships a ready-made version called OrbitControls. You give it the camera and the canvas, and it listens for the mouse, touch, and wheel, does the trigonometry, and moves the camera for you. The hero stage above is OrbitControls with one extra setting, autoRotate, so it shows itself off until you grab it.

The second is game-driven. In a racing game or a platformer the player does not steer the camera; the camera has a job, "stay a little behind and above the hero," and does it every frame without asking. That one you write yourself, and it is shorter than you would guess: figure out where the camera wants to be, move it a fraction of the way there, and point it at the player. Three lines, the same three in a big-studio game and in your first one.

One rule ties them together, and it is the rule beginners break first: one driver at a time. If OrbitControls and your follow code are both moving the camera, they fight every frame and the picture shakes. The "Try it" stage has a Mode switch that hands the camera from one to the other, and the code shows exactly how.

Simple definition: camera controls are code that moves the camera every frame based on something other than a fixed number: the user's drags and scrolls (OrbitControls), or the game's own rules (a follow camera you write). The camera is still the same PerspectiveCamera from Part 2 with the same position and lookAt. Controls just decide who gets to set them.


How It Works

Addons, OrbitControls, follow

We keep the setup from Part 1 (scene, camera, renderer, lights) and the delta-time loop from Part 7. Everything new on this page is about who moves the camera between frames.

1. Addons: the tools that are not in the box

The THREE object you have been importing is the core library: scenes, cameras, geometries, materials, lights. It is already big, so the three.js team keeps a second shelf of tools next to it called addons: camera controls, loaders for 3D model files, post-processing effects, helpers of every kind. They live in a folder named examples/jsm/ on the same CDN, and you pull one in with its own import line. OrbitControls is the most-used addon by a wide margin; most three.js projects start with the two import lines you are about to see.

It works with no extra setup because the importmap from Part 1 has always had two lines, and until now we only used the first.

index.html · the importmap from Part 1
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"   // ← this one
  }
}
</script>

The second line is a nickname. Anywhere you write 'three/addons/' at the start of an import path, the browser swaps in the long CDN address for the examples/jsm/ folder. So 'three/addons/controls/OrbitControls.js' means "the file controls/OrbitControls.js inside that folder." Nothing else in your setup changes; the map was ready for this page all along.

2. OrbitControls in two lines, plus the one you must not forget

Creating the controls is one line: new OrbitControls(camera, renderer.domElement). The first argument is the camera it is allowed to move. The second is the element it listens on: renderer.domElement is the <canvas> the renderer draws into. From then on, three gestures on that canvas move the camera. Because it listens only on the canvas, the rest of your page still scrolls and clicks like normal.

drag → orbit

enableRotate

The camera circles around controls.target like a moon around a planet, always facing it. Left-drag on a mouse, one finger on a phone.

wheel → zoom

enableZoom

Moves the camera closer to or farther from the target along a straight line. Mouse wheel, or a two-finger pinch. minDistance and maxDistance put fences on it.

right-drag → pan

enablePan

Slides the camera and the target together, so the whole scene shifts sideways. Right-button drag, or a two-finger drag. Often turned off in games.

Out of the box the controls feel stiff: the camera stops dead the instant your finger does. enableDamping fixes that. With damping on, a drag gives the camera momentum and it glides to a stop over a few frames, like a spinning globe. dampingFactor is how quickly the glide dies out: the default 0.05 is a gentle coast, a bigger number stops sooner.

And here is the catch that trips up nearly everyone. Damping happens between your drags, and the controls have no loop of their own. They can only glide if you call controls.update() every frame inside animate. Same for autoRotate. Forget the call and both settings silently do nothing: the controls still work, they just feel exactly like before. Put controls.update() in the loop the moment you create the controls and you will never hunt for this bug.

orbit.js
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';   // the addon

// ...the setup from Part 1: scene, camera, renderer, lights, clock...

// Give the controls the camera to move and the canvas to listen on
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;    // glide to a stop instead of freezing
controls.dampingFactor = 0.05;    // smaller = longer glide

function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);
  controls.update();   // REQUIRED for damping and autoRotate: run it every frame
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

This is the hero stage, minus its settings. Notice that we never set camera.position in the loop anymore; the controls own it now. If you ever tear a scene down, controls.dispose() removes its listeners from the canvas, but a single-page demo like this never needs it.

3. Settings: target, fences, and the floor

A fresh OrbitControls orbits around the origin and lets the camera go anywhere: inside your objects, a mile away, or straight underneath the floor. Six settings tame it, one line each. The most important is controls.target, the point the camera circles and always looks at. It is a Vector3, so you set it with target.set(x, y, z), aimed at whatever should be centered: our diorama's objects sit about half a unit above the platform, so the target is (0, 0.5, 0).

minDistance and maxDistance fence the zoom: the camera can never get closer to the target than the first or farther than the second. maxPolarAngle is the floor lock. The polar angle is how far the camera has swung down from straight overhead, in radians (Part 6): 0 is looking straight down, Math.PI / 2 is level with the target, and Math.PI is looking up from underneath. The default allows the full Math.PI, so users can drag themselves under the ground; Math.PI / 2 stops them at floor level. enablePan = false turns off right-drag sliding, which you want on a game menu or a product viewer where the object should stay centered. And autoRotate with autoRotateSpeed makes the camera orbit on its own until the user grabs it: 2.0 means one lap every 30 seconds. Like damping, it only moves if controls.update() runs each frame.

settings.js
controls.target.set(0, 0.5, 0);        // the point you orbit around; the camera always looks here
controls.minDistance = 4;              // can't zoom in closer than 4 units...
controls.maxDistance = 12;             // ...or out farther than 12
controls.maxPolarAngle = Math.PI / 2;  // never swing below the floor (Math.PI would allow it)
controls.enablePan = false;            // no right-drag sliding: lock it down like a game menu
controls.autoRotate = true;            // showcase spin until the user grabs it (needs update() too)
controls.autoRotateSpeed = 1.5;        // 2.0 = one lap every 30 seconds
controls.saveState();                  // remember this as "home" so controls.reset() can return to it

These are the hero stage's exact settings, and every slider and toggle in "Try it" is one of these lines. saveState() is a small bonus: call it once after setup, and controls.reset() later snaps the camera and target back to that saved spot. That is the Reset camera button.

4. A follow camera: the game drives

Now the other grip. A follow camera has one idea in it. Every frame, work out where the camera should be: the player's position plus a fixed offset, a Vector3 like (0, 3, 6) meaning "3 units up and 6 units behind." Then, instead of teleporting there, move the camera a fraction of the way and point it at the player. That is what lerp does: camera.position.lerp(desired, 0.1) moves the camera 10% of the remaining distance toward desired. Do that every frame and it covers big gaps fast and small gaps slowly, so it eases into place instead of snapping. The word is short for linear interpolation, but "move part of the way there" is all you need to remember.

The beginner version, a plain lerp(desired, 0.1), works and is fine to start with. Its flaw is the one from Part 7: it moves 10% per frame, so on a 120 Hz screen the camera catches up twice as fast. The fix is a fraction that depends on dt: 1 - Math.pow(0.001, dt). It is built so that after one full second only 0.1% of the gap is left, no matter how many frames that second was chopped into. Make the 0.001 bigger, say 0.1, and more gap is left after a second: a floatier, laggier camera. That is the Smoothness slider.

Last, the handoff. When the follow camera is driving, OrbitControls must let go completely: set controls.enabled = false so it ignores drags, and stop calling controls.update(), because update() still re-points the camera at controls.target even when disabled. Two hands on the wheel, and the camera jitters. An if on a mode variable is all it takes.

follow.js
let mode = 'orbit';                                  // 'orbit' (you drive) or 'follow' (the game drives)
const offset = new THREE.Vector3(0, 3, 6);           // where the camera wants to be: 3 up, 6 behind the player

function followCamera(dt) {
  const desired = player.position.clone().add(offset);
  camera.position.lerp(desired, 1 - Math.pow(0.001, dt));   // ease toward it, same speed on every device
  camera.lookAt(player.position);
}

function setMode(next) {
  mode = next;
  controls.enabled = (mode === 'orbit');             // one driver at a time
}

function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);
  movePlayer(dt);                                    // the player drives itself in a figure-eight
  if (mode === 'orbit') {
    controls.update();                               // OrbitControls moves the camera
  } else {
    followCamera(dt);                                // our code moves the camera; update() is NOT called
  }
  renderer.render(scene, camera);
}

This is the "Try it" stage's loop. movePlayer is two Math.sin calls, x = Math.sin(t) * 2.8 and z = Math.sin(2 * t) * 1.4 with t growing by dt, and is not the lesson; in Part 10 the player moves because you press keys, and the same follow camera works unchanged.


Try It

Drive the camera

The stage is the hero's diorama plus a small white player cube that drives itself in a slow figure-eight. In Orbit mode you hold the camera: drag to look around, scroll or pinch to zoom, and use the first card of controls to change the lines from settings.js. In Follow mode the game holds it: the orbit controls dim, the second card lights up, and the camera chases the player using follow.js. The live code under the controls rewrites itself as you change things.

Scrolling with the pointer over the stage zooms instead of scrolling the page. That is OrbitControls doing its job on the canvas; move the pointer off the stage to scroll normally.

Mode the mode variable in follow.js: which code moves the camera each frame

OrbitControls · settings.js

Damping controls.enableDamping; needs update() in the loop
0.05
4
12
Limits controls.maxPolarAngle and controls.enablePan
Auto-rotate controls.autoRotate; also needs update()
2.0

Follow camera · follow.js

3.0
6.0
0.001 · tight
Live code: what the controls are setting
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.5, 0);
controls.enableDamping = true;   controls.dampingFactor = 0.05;
controls.minDistance = 4;   controls.maxDistance = 12;
controls.maxPolarAngle = Math.PI / 2;   // stop at floor level
controls.enablePan = false;
controls.autoRotate = false;   controls.autoRotateSpeed = 2;
controls.enabled = true;   // Orbit mode: you drive
// inside animate(), every frame:
controls.update();   // damping and autoRotate are computed here
  1. Turn Damping off, drag the stage hard and let go. Then turn Damping on and do it again. With damping off the camera freezes the instant your pointer stops. With it on, the camera keeps coasting to a stop, and the Damping factor slider decides how long: 0.02 spins like a well-oiled globe, 0.2 barely coasts. The only difference in the code is enableDamping, and none of it would work without controls.update() in the loop.
  2. Drag Max distance down to 6 and try to scroll out. The camera hits an invisible wall; you cannot get farther from the target than maxDistance, however hard you scroll. Push Min distance up until it nearly meets it and the zoom has almost no room left. Then turn off "Lock to above floor" and drag downward past level: you are under the platform, looking up at the undersides. Turn the lock back on and the camera pops back above the floor.
  3. Switch to Follow, then drag Smoothness all the way up. In Follow mode the camera glides behind the white cube and turns with it, and dragging does nothing, because controls.enabled is false and update() is no longer called. At 0.5 the camera lags far behind the player like a drone that is slow to react, swinging wide on every turn; at 0.001 it is glued on. Raise Follow height for a top-down view, or set Follow distance to 3 for a close chase.

Watch Out

Common mistakes

Camera-control bugs feel like the controls are broken, when really one line is missing or one line too many is running. Here are the four you will hit first.

Damping or auto-rotate does nothing

You set enableDamping = true or autoRotate = true. Dragging still works, but the camera stops dead and never spins on its own.

Fix: call controls.update() inside animate(). The glide and the auto-spin are computed in that call, so without it they can never happen. Plain dragging works without update(), which is why this bug hides so well.

The camera jitters and fights

You added a follow camera and now the view shakes, snaps back, or slides toward the wrong spot every frame.

Fix: two drivers are moving the camera. When your own code positions the camera, set controls.enabled = false and stop calling controls.update(), which re-aims the camera at controls.target even when disabled. One driver per frame: an if (mode === 'orbit') around the call.

The camera goes under the floor

A user drags down a little too far and is suddenly looking up at the bottom of your ground plane, which is invisible from below.

Fix: controls.maxPolarAngle = Math.PI / 2;. The default is Math.PI, which allows a full swing underneath. Math.PI / 2 stops at floor level; use a bit less, like Math.PI / 2 - 0.05, to keep a sliver of height so the floor never turns edge-on.

The page won't scroll over the canvas

Your mouse wheel zooms the scene instead of scrolling the page, and on a phone, swiping on the canvas does not scroll either.

Fix: this one is expected. OrbitControls captures wheel and touch events on the canvas you gave it, and only there. Keep the canvas a sensible size instead of wrapping the whole page in it, and the rest of the page scrolls normally. If a viewer should not zoom at all, controls.enableZoom = false gives the wheel back to the page.


Your Turn

Check your understanding

Your orbit camera moves when you drag it, but the smooth gliding you turned on with enableDamping isn't happening. The camera just stops the moment your finger does. What's missing, and where does it go?

Your answer:

Sample answer: controls.update(); inside the animation loop. Dragging moves the camera immediately, which is why the controls seem to work, but the glide after you let go is computed a little at a time on each call to update(). No call, no glide. The same is true of autoRotate. Put controls.update() in animate() right before renderer.render, and damping starts working with no other change.


Check Yourself

Quick quiz

1. What is controls.target?

2. Why does controls.update() have to run every frame?

3. In a follow camera, what does camera.position.lerp(desired, 0.1) do each frame?

Keep learning

The camera is no longer a tripod. You can import an addon, hand the camera to OrbitControls with damping and sensible limits, keep controls.update() in the loop, and write a follow camera that eases behind a player with lerp and lookAt. Next, the player stops driving itself: you read the keyboard and mouse and steer a cube around the grid with WASD.

Part of the Games and Animations with Three.js tutorial series.