Bash.tv → GitHub → itch.io

Camera Controller

A 2D camera that follows the player smoothly, zooms, shakes, stays inside the level and converts between screen and world positions.

Files: camera-controller.js (the component, no dependencies) and camera-controller.test.mjs (6 tests). Copy camera-controller.js into your game, for example to src/components/, and import it as an ES module.

Usage

import { createCamera } from "./camera-controller.js";
const cam = createCamera({ width: 480, height: 270, bounds: { x: 0, y: 0, w: level.w, h: level.h }, smooth: 8, deadzone: { w: 60, h: 40 } });
cam.follow(player);
function frame(dt) {
  cam.update(dt);
  ctx.save(); cam.apply(ctx); drawWorld(); ctx.restore();   // HUD after restore stays put
}
cam.shake(0.5);                                             // on a big hit
const world = cam.toWorld(input.pointer.x, input.pointer.y);

API

cam.x, cam.y centre of the view in world units; cam.offset → current shake offset

Engines

Engine Notes
Vanilla / Canvas 2D apply(ctx).
PixiJS run update(), then set world.pivot to (cam.x + offset.x, cam.y + offset.y), world.position to the screen centre and world.scale to cam.zoom.
Phaser use this.cameras.main (it has follow, deadzone, shake and bounds).
Three.js for 2D or top-down games, copy cam.x / cam.y into an OrthographicCamera’s position each frame.

Tests

Node tests: follow and smoothing, deadzone, bounds, small levels centred, zoom easing, shake decay and the off switch, screen and world conversion.

Run them with node --test toolkit/components/camera-controller/ (Node 20 or newer, nothing to install).