Skip to content

Camera Rigs ​

A Camera Rig component makes a camera follow something, with no script. Add it to the camera entity, pick a target and a view, and it handles following, the mouse, walls and switching views. Reach for a script only when a game needs a camera no view covers.

ModeThe viewHow the player turns it
thirdPersonBehind the character. Set shoulder for over-the-shoulderClick to capture the mouse
firstPersonFrom the character's eyes; height is the eye heightClick to capture the mouse
orbitAround something, for a model viewer or a menuDrag
isometricFixed angle from above and to the sideFixed
topDownLooking downFixed
sideFrom the side, for a platformerFixed

In the editor: select the camera, Add Component → Camera Rig, and pick the target. From a script:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import { CameraRigComponent } from "@relu-interactives/spatial-ecs/components";

export default class SetUpCamera extends Behaviour {
  protected init() {
    const player = this.world.getEntityByName("Player");
    if (!player) return;
    this.world.addComponent(
      this.entityId,
      new CameraRigComponent({ mode: "thirdPerson", target: player.entityId, shoulder: 0.6 }),
    );
  }
}

Settings ​

Anything left null uses the usual value for the view.

SettingWhat it does
targetThe entity to follow
distance, minDistance, maxDistance, scrollZoomHow far back, and whether the wheel changes it
heightHeight above the target's origin to look at; the eye height in first person
shoulderMetres to the right of the target
followTimeSeconds to catch up. 0.06 is tight, 0.3 is relaxed, 0 is locked on
heightFollowTimeThe same for height, so a jump doesn't shake the view
deadZoneMetres the target moves before a fixed view follows
yawDegrees, pitchDegreesThe angle. Fixed views hold it; the others start there
minPitchDegrees, maxPitchDegreesHow far the player can turn up and down
sensitivity, invertYHow the mouse feels
lookpointerLock, drag, none, or auto for the usual one
avoidWalls, wallPaddingCome forward when a wall gets in the way. Needs colliders on the walls
blendTimeSeconds to ease when mode changes

An isometric look comes from a narrow lens: set the Camera's field of view to about 25 and let the view's own distance do the rest.

Moving the player ​

this.cameras.moveDirection(right, forward) turns input into a direction on the ground, so forward means away from the camera in every view, including looking straight down. Use it and one controller works with all of them. A character needs a dynamic rigid body with rotation locked.

ts
import { Behaviour, dampAngle, KeyboardKeys } from "@relu-interactives/spatial-ecs";
import type { FloatInput } from "@relu-interactives/spatial-ecs";
import { PhysicsComponent } from "@relu-interactives/spatial-ecs/components";

export default class PlayerController extends Behaviour {
  data = {
    speed: 5 as FloatInput,
    sprintSpeed: 8 as FloatInput,
    jumpSpeed: 6 as FloatInput,
    turnTime: 0.07 as FloatInput,
  };

  private facing = 0;

  protected onUpdate() {
    const rb = this.getComponent(PhysicsComponent)?.rigidBody;
    if (!rb) return;

    // a cutscene has the camera, so the player waits
    const active = !this.cameras.isPlaying;
    const { world } = this;
    const right = active ? Number(world.getKey(KeyboardKeys.D)) - Number(world.getKey(KeyboardKeys.A)) : 0;
    const forward = active ? Number(world.getKey(KeyboardKeys.W)) - Number(world.getKey(KeyboardKeys.S)) : 0;

    const move = this.cameras.moveDirection(right, forward);
    const length = Math.hypot(move.x, move.z);
    const sprinting = active && world.getKey(KeyboardKeys.ShiftLeft);
    const speed = sprinting ? this.data.sprintSpeed : this.data.speed;
    const vel = rb.linvel();

    if (length > 0.01) {
      // keep vel.y, or gravity stops working
      rb.setLinvel({ x: (move.x / length) * speed, y: vel.y, z: (move.z / length) * speed }, true);
      this.facing = dampAngle(this.facing, Math.atan2(move.x, move.z), this.data.turnTime, this.deltaTime);
      const half = this.facing / 2;
      rb.setRotation({ x: 0, y: Math.sin(half), z: 0, w: Math.cos(half) }, true);
    } else {
      rb.setLinvel({ x: 0, y: vel.y, z: 0 }, true);
    }

    if (active && Math.abs(vel.y) < 0.05 && world.getKeyDown(KeyboardKeys.Space)) {
      rb.setLinvel({ x: vel.x, y: this.data.jumpSpeed, z: vel.z }, true);
    }
  }
}

Switching views ​

Set mode and the camera eases there over blendTime, keeping the way it's facing:

ts
import { Behaviour, KeyboardKeys } from "@relu-interactives/spatial-ecs";
import { CameraRigComponent } from "@relu-interactives/spatial-ecs/components";

export default class ToggleView extends Behaviour {
  protected onUpdate() {
    const rig = this.getComponent(CameraRigComponent);
    if (rig && this.world.getKeyDown(KeyboardKeys.V)) {
      rig.mode = rig.mode === "firstPerson" ? "thirdPerson" : "firstPerson";
    }
  }
}

Cutscenes ​

this.cameras.play() takes the camera, runs shots in order, and gives it back. The player's camera keeps running underneath, so the way back lands exactly on it with no jump, even if the character moved. It works over a Camera Rig or a camera your own script moves.

Place empty entities in the scene to mark the shots, and name them.

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export default class GateCutscene extends Behaviour {
  async opening() {
    await this.cameras.play(
      [
        // a crane move, easing in from wherever the player was looking
        { at: "Crane Start", moveTo: "Crane End", lookAt: "Gate", duration: 3, blendIn: 0.8 },
        // a cut to a close-up on a longer lens
        { at: "Gate Close-up", lookAt: "Player", duration: 2, fov: 28 },
      ],
      { blendOut: 0.6 },
    );
    // the player has the camera back here
  }
}

A shot's at, moveTo and lookAt take a name, an entity id, an entity field from data, or a position. A lookAt on a moving entity keeps tracking it.

While this.cameras.isPlaying is true, gameplay should wait, as the controller above does. this.cameras.stop() ends a cutscene early for a Skip button. Don't use Escape to skip while the mouse is captured: the browser takes that key to release the mouse, and the game never sees it.

this.cameras.shake(strength, seconds) shakes whatever the camera is doing: 0.05 for a footstep, 0.35 for an explosion.

A camera of your own ​

Write a camera in onLateUpdate, not onUpdate. It runs after everything else has moved, including animation, so it reads where things will really be drawn. In onUpdate, a camera trails by a frame depending on which script ran first.

Read the target's Transform, and smooth with damp:

ts
import { Behaviour, damp } from "@relu-interactives/spatial-ecs";
import type { FloatInput, TextInput } from "@relu-interactives/spatial-ecs";
import { TransformComponent } from "@relu-interactives/spatial-ecs/components";

export default class RailCamera extends Behaviour {
  data = { targetName: "Player" as TextInput, followTime: 0.2 as FloatInput };

  private target: TransformComponent | null = null;

  protected onLateUpdate() {
    if (!this.target) {
      const found = this.world.getEntityByName(this.data.targetName);
      if (!found) return;
      this.target = this.world.getComponent(found.entityId, TransformComponent) ?? null;
      if (!this.target) return;
    }
    // the camera runs along a rail, following the player's x
    this.transform.position.x = damp(
      this.transform.position.x,
      this.target.position.x,
      this.data.followTime,
      this.deltaTime,
    );
  }
}

What moves in onLateUpdate reaches the screen the same frame for the script's own entity and for cameras. Move anything else in onUpdate.

Why a camera jitters ​

Physics runs at a fixed rate, 50 Hz by default, and the screen at its own. A body written straight from physics moves an uneven distance each frame, and one frame in six not at all on a 60 Hz screen. A smooth camera following that makes the character shake.

The engine shows moving bodies between physics steps, so this.transform moves evenly. It only helps if the camera reads that value:

Camera followsA character at 6 m/s, pixels of shake per frame at 60 HzAt 144 Hz
The raw body, before the engine interpolated6.510.7
The raw body, rigidBody.translation(), today3.51.3
transform, in a script0.140.05
A Camera Rig0.030.02

Measured on a 1080p screen by core/camera/cameraSmoothness.test.ts, with real physics.

Common mistakes ​

MistakeWhy it failsDo instead
Writing a follow camera at allThe usual views are one componentAdd a Camera Rig
rigidBody.translation() in a cameraIt moves in uneven steps, so the view shakesRead this.transform, or the target's TransformComponent
A camera in onUpdateIt reads last frame's animation, and depends on script orderonLateUpdate
Math.min(1, speed * this.deltaTime)It isn't the same at every frame ratedamp(current, target, seconds, this.deltaTime)
Setting camera.positionThe transform sync overwrites itthis.transform, or a Camera Rig
rb.setLinvel({ x, y: 0, z })Kills gravityKeep vel.y
Reading yaw back out of a quaternionEuler angles flip at some rotationsKeep yaw and pitch as numbers
consumeMouseDelta() in a script alongside a rigOnly one reader gets each movementSet the rig's look to none if a script owns the mouse

Try it ​

examples/camera-rigs in the engine repository is all of this running: a capsule on real physics, number keys for each view, walls, a cutscene and a shake.