dino-ge

5. Move the camera and switch scenes

Core guide

A camera chooses which part of the world is visible. A scene owns a set of objects and their update logic. Moving the camera can reveal another room within the same scene. Replacing the scene can take you to a different level or menu.

Run the demo · View the source

Select Cross room to pan from the Gatehouse to the Amber Vault. Select Enter exit to fade into a new scene.

Pan between rooms and open an exit

Keep the <head> from the first scene. Replace the contents of <body> with:

<div id="game" style="width: 360px; max-width: 100%; height: 220px"></div>
<button id="cross" disabled>Cross room</button>
<button id="exit" disabled>Enter exit</button>
<p id="status" role="status"></p>

Save this as main.js:

import { Circle, Engine, Rectangle, Scene, Text, Vector2 } from 'dino-ge';

const status = document.querySelector('#status');
const cross = document.querySelector('#cross');
const exit = document.querySelector('#exit');
let cameraTarget = 0;

class Rooms extends Scene {
  onLoad() {
    for (const [x, colour] of [[0, '#376057'], [360, '#3c526d']]) {
      this.add(new Rectangle({ position: new Vector2(x, 0), width: 360, height: 220, colour }));
      this.add(new Text({
        position: new Vector2(x + 22, 32), text: x ? 'Amber Vault' : 'Gatehouse',
        colour: '#edf5f3', fontSize: '19', zIndex: 1,
      }));
    }
    this.explorer = new Circle({ position: new Vector2(80, 110), radius: 12, colour: '#ffc46f', zIndex: 2 });
    this.add(this.explorer);
    cross.disabled = false;
    status.textContent = 'Gatehouse';
  }

  update() {
    const position = Engine.camera.position;
    position.x += (cameraTarget - position.x) * 0.12;
  }
}

class BeyondTheRuins extends Scene {
  onLoad() {
    Engine.camera.reset();
    this.add(new Text({ position: new Vector2(22, 70), text: 'Outside the ruins', colour: '#edf5f3', fontSize: '22' }));
    status.textContent = 'Outside the ruins';
  }
}

const rooms = new Rooms();
const game = new Engine({
  onLoad() {
    Engine.currentScene = rooms;
  },
}, { containerId: 'game', width: '100%', height: '100%', backgroundColour: '#183035' });

cross.addEventListener('click', () => {
  rooms.explorer.transform.position.x = 440;
  cameraTarget = 360;
  cross.disabled = true;
  exit.disabled = false;
  status.textContent = 'Amber Vault';
});
exit.addEventListener('click', () => {
  exit.disabled = true;
  game.transitionTo(new BeyondTheRuins(), { type: 'fade', duration: 0.5 });
});

The two room backgrounds live side by side in Rooms. Cross room moves the explorer to x = 440 and sets cameraTarget to 360, the left edge of the vault. Each update closes a fraction of the gap between the camera and that target. The explorer and rooms keep their world positions as the view pans. This short demo eases per frame, so the speed depends on the refresh rate.

Enter exit calls game.transitionTo(new BeyondTheRuins(), { type: 'fade', duration: 0.5 }). Halfway through the half-second fade, the engine activates the destination scene. It resets the camera and calls the destination’s onLoad(), which adds the new text. The room objects belong to Rooms, so they are no longer drawn. Use Engine.currentScene = new BeyondTheRuins() in the click handler if you want an immediate switch.

Follow the explorer instead of a fixed target

In the example above, replace Rooms.update() with the method below. Remove let cameraTarget = 0 and cameraTarget = 360; the camera now follows this.explorer directly. Read game.width and game.height each time so the camera uses the current viewport size after a resize.

update() {
  const world = { x: 0, y: 0, width: 720, height: 220 };
  Engine.camera.follow(this.explorer, game.width, game.height, world);
}

Reload and select Cross room. The camera jumps to the explorer’s rendered centre, as far as the bounds allow. The fourth argument is the world rectangle, in pixels. If the viewport is larger than the world along one axis, the camera centres that axis. Call Engine.camera.getViewportBounds(game.width, game.height) to read the visible rectangle in world coordinates.

To ease into the new position, remove the Rooms.update() method and add the following fixedUpdate() next to onLoad() in the callbacks passed to new Engine(). The guard limits following to the rooms scene, so the camera stays at the origin after you use the exit.

fixedUpdate() {
  if (Engine.currentScene !== rooms) return;
  Engine.camera.followSmooth(rooms.explorer, game.width, game.height, 1 / 60, {
    response: 5,
    bounds: { x: 0, y: 0, width: 720, height: 220 },
  });
},

1 / 60 is the elapsed simulation time in seconds for one fixed step. A higher response approaches the target faster. With bounds, the camera first moves any out-of-range position back inside the valid range, for example after a resize or zoom, then eases towards the explorer.

To try the bounded follow demo from a repository checkout, run npm run build -w dino-ge and npm run example, then open Bounded camera follow. Select Jump surveyor with Smooth follow on and off to compare the movement. Toggle the bounds at an edge, then zoom out to see how the larger viewport is centred.

Camera · Scene · Engine