TExcelTAD
Home › 3D Web Games with Three.js › OrbitControls

OrbitControls

OrbitControls lets the user turn the camera around a point by dragging, zoom with the wheel or a pinch, and pan with the right button or two fingers. It's the camera of model viewers, level editors, character-select screens, turn-based strategy and puzzle games, and the first thing to add to any scene while you develop it, because you can't debug a scene you can only see from one angle.

js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1, 0);      // the point to orbit around
controls.update();                 // apply after changing target or the camera by hand

How it works: spherical coordinates

The controls don't store the camera's rotation. They store the camera's position relative to target as spherical coordinates: a distance radius, a polar angle phi measured down from straight up, and an azimuth theta around the vertical axis. Dragging changes phi and theta, zooming changes radius, and the camera position is rebuilt from them every update(), followed by camera.lookAt(target). This model does the same conversion (THREE.Spherical and Vector3.setFromSpherical in Three.js):

js · try it yourself
// Camera position around a target from spherical coordinates (Three.js convention: phi from +Y, theta around Y from +Z).
function fromSpherical(radius, phiDeg, thetaDeg, target = [0, 0, 0]) {
  const phi = phiDeg * Math.PI / 180, theta = thetaDeg * Math.PI / 180;
  const s = radius * Math.sin(phi);
  return [target[0] + s * Math.sin(theta), target[1] + radius * Math.cos(phi), target[2] + s * Math.cos(theta)];
}
const fmt = (v) => v.map((n) => (Math.abs(n) < 5e-7 ? 0 : n).toFixed(2)).join(', ');

console.log('phi 90, theta   0:', fmt(fromSpherical(10, 90, 0)));    // level, in front (+Z)
console.log('phi 90, theta  90:', fmt(fromSpherical(10, 90, 90)));   // level, to the right (+X)
console.log('phi 45, theta   0:', fmt(fromSpherical(10, 45, 0)));    // 45° above the horizon
console.log('phi 10, theta   0:', fmt(fromSpherical(10, 10, 0)));    // nearly straight down
console.log('phi 60, theta 180, target (0,1,0):', fmt(fromSpherical(5, 60, 180, [0, 1, 0])));
phi 90, theta   0: 0.00, 0.00, 10.00
phi 90, theta  90: 10.00, 0.00, 0.00
phi 45, theta   0: 0.00, 7.07, 7.07
phi 10, theta   0: 0.00, 9.85, 1.74
phi 60, theta 180, target (0,1,0): 0.00, 3.50, -4.33

This is why limits are given as angles: maxPolarAngle = Math.PI / 2 (90°) stops the camera at the horizon so players can't look at the scene from below the floor.

A model viewer

The setup below is what most "inspect this item" screens use: damping for a smooth, weighty feel, limits on distance and angle, a slow auto-rotate that stops while the user interacts, and double-click to reset.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block; touch-action: none }
#hint { position: fixed; left: 10px; top: 8px; color: #fff; font: 12px system-ui, sans-serif; text-shadow: 0 1px 2px #000; pointer-events: none }</style>
<div id="hint">Drag to orbit, wheel to zoom, right-drag to pan, double-click to reset</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.AgXToneMapping;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#20242e');
scene.environment = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(), 0.04).texture;
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 100);
camera.position.set(3, 2, 4);
addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

// The "item": a little sword built from primitives.
const sword = new THREE.Group();
const steel = new THREE.MeshStandardMaterial({ color: '#d8dde3', metalness: 1, roughness: 0.25 });
const gold = new THREE.MeshStandardMaterial({ color: '#e0b04a', metalness: 1, roughness: 0.35 });
const leather = new THREE.MeshStandardMaterial({ color: '#5a3a26', roughness: 0.8 });
const blade = new THREE.Mesh(new THREE.BoxGeometry(0.16, 1.8, 0.04), steel);
blade.position.y = 1.25;
const tip = new THREE.Mesh(new THREE.ConeGeometry(0.113, 0.25, 4), steel);
tip.rotation.y = Math.PI / 4;
tip.scale.z = 0.35;
tip.position.y = 2.27;
const guard = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.08, 0.12), gold);
guard.position.y = 0.32;
const grip = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.05, 0.45, 12), leather);
grip.position.y = 0.06;
const pommel = new THREE.Mesh(new THREE.SphereGeometry(0.08, 16, 12), gold);
pommel.position.y = -0.2;
sword.add(blade, tip, guard, grip, pommel);
sword.position.y = -0.9;
scene.add(sword);
const floor = new THREE.Mesh(new THREE.CircleGeometry(1.5, 48), new THREE.MeshStandardMaterial({ color: '#2c313c' }));
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.1;
scene.add(floor);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.3, 0);
controls.enableDamping = true;          // needs controls.update() every frame
controls.dampingFactor = 0.08;
controls.minDistance = 1.5;
controls.maxDistance = 8;
controls.maxPolarAngle = THREE.MathUtils.degToRad(100);   // a little below the horizon, not under the floor
controls.autoRotate = true;
controls.autoRotateSpeed = 1.5;
controls.addEventListener('start', () => { controls.autoRotate = false; });
controls.update();
controls.saveState();                   // remembered for reset()
renderer.domElement.addEventListener('dblclick', () => { controls.reset(); controls.autoRotate = true; });

const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
  timer.update(t);
  controls.update(Math.min(Math.max(timer.getDelta(), 0), 0.1));   // with a delta, autoRotate is frame-rate independent
  renderer.render(scene, camera);
});
</script>

Settings worth knowing

Property Default Use
target (0, 0, 0) the orbit centre; move it to follow a selected unit
enableDamping, dampingFactor false, 0.05 inertia; requires update() every frame
minDistance, maxDistance 0, ∞ zoom limits (minZoom/maxZoom for orthographic cameras)
minPolarAngle, maxPolarAngle 0, π vertical limits (π/2 = horizon)
minAzimuthAngle, maxAzimuthAngle −∞, ∞ horizontal limits, e.g. a diorama seen only from the front
enableRotate, enableZoom, enablePan true switch features off
screenSpacePanning true pan in the screen plane; false pans along the ground (what MapControls uses)
zoomToCursor false zoom toward the point under the mouse, like map apps
autoRotate, autoRotateSpeed false, 2 turntable; pass a delta to update(dt) for frame-rate independence
mouseButtons, touches rotate/dolly/pan remap buttons and gestures

Events: 'start' and 'end' when the user begins and stops interacting, 'change' whenever the camera moves.

Note: dampingFactor is applied per update() call, so damping feels slightly different at 60 and 144 Hz. For a model viewer nobody notices; for gameplay cameras, write your own damping with dt (see Third-Person Camera).

Render on demand

A model viewer or a turn-based game doesn't need 60 renders per second while nothing moves. Render only when the controls change the camera (without damping, since damping keeps moving after the input stops):

js
controls.addEventListener('change', () => renderer.render(scene, camera));
renderer.render(scene, camera);   // the first frame

That saves battery on laptops and phones, and keeps the fans quiet, which players notice in a browser tab.

The other controls in the addons

Controls Behaviour Game use
MapControls OrbitControls preset: left-drag pans along the ground, right-drag rotates RTS, city builders, maps
TrackballControls / ArcballControls free rotation without a fixed "up" molecule viewers, space; rarely games
FlyControls 6-DOF flying with keys and mouse debug fly-cam, space sims
FirstPersonControls mouse-look without pointer lock quick walk-throughs
PointerLockControls mouse-look with the pointer locked first-person games (First-Person Controls)
TransformControls gizmo to move/rotate/scale an object in-game level editors
DragControls drag objects on a plane with the mouse puzzles, board games

All of them take (camera or object, domElement), and all have dispose() to remove their event listeners when you switch cameras or leave a screen. Forgetting dispose() leaves the old controls listening and moving a camera you no longer show.

Test yourself

You enabled enableDamping and the camera stops responding smoothly, or freezes after you release the mouse. What is missing?

  1. controls.saveState()
  2. Calling controls.update() every frame in the animation loop
  3. controls.autoRotate = true
  4. camera.updateProjectionMatrix()

How do you stop players orbiting below the floor?

  1. minDistance = 1
  2. maxPolarAngle = Math.PI / 2 (or a bit less)
  3. enablePan = false
  4. maxAzimuthAngle = 0

Which preset suits an RTS camera that pans along the ground with the left mouse button?

  1. TrackballControls
  2. MapControls
  3. PointerLockControls
  4. FlyControls