Platformer 4: Camera Follow
So far the whole level fit on the screen. Real levels are much bigger than the screen, so the game needs a camera: a rectangle the size of the screen that moves through the level and decides which part is visible. This step makes the level 90×22 tiles (1440×352 pixels, three screens wide) and adds a camera that follows the player smoothly.
World space and screen space
Everything in the game now has a world position: where it is in the level. The camera has a world position too, cam.x, cam.y, the top-left corner of what you see. Turning a world position into a screen position is a subtraction:
screenX = worldX - cam.x;
screenY = worldY - cam.y;You don't need to do that subtraction for every object. Canvas can do it for you: translate the whole drawing once, draw everything at its world position, then restore.
ctx.save();
ctx.translate(-Math.round(cam.x), -Math.round(cam.y)); // integer offset: crisp tiles, no shimmering
drawTiles();
drawPlayer();
ctx.restore();
drawHud(); // HUD stays in screen spaceTip: Always round the camera offset. A camera at
x = 100.37draws every tile edge between two pixels; the edges blur and shimmer as the camera moves. That's one of the "integer pixel positions" rules from the field notes.
The game logic, collisions and tile map don't change at all. The camera is purely a drawing concern.
Following the player
The simplest camera centers the player: cam.x = player.x - W / 2. It works, but every tiny movement shakes the whole world. Three refinements make it pleasant:
| Refinement | What it does |
|---|---|
| Dead zone | A box in the middle of the screen where the player can move without the camera moving |
| Smoothing | The camera moves toward its target a fraction of the distance each update, so it eases instead of snapping |
| Clamping | The camera never shows anything outside the level: 0 ≤ cam.x ≤ levelWidth - W |
Smoothing that doesn't depend on the frame rate
The obvious smoothing is cam.x += (target - cam.x) * 0.1 every frame. The problem: "every frame" means the camera is twice as fast at 120 Hz as at 60 Hz. The fix is exponential damping: use 1 - Math.exp(-speed * dt) as the fraction. Over the same amount of time it covers the same distance, whatever the step size.
const W = 480, LEVEL_W = 1440;
const clampCam = (x) => Math.max(0, Math.min(LEVEL_W - W, x));
console.log('clamped:', [-50, 0, 300, 960, 1200].map(clampCam).join(' '));
// The camera starts at 0 and chases a target at 200 for half a second.
function naive(hz) {
let cam = 0;
for (let i = 0; i < hz / 2; i++) cam += (200 - cam) * 0.1; // a fixed fraction per frame
return cam.toFixed(1);
}
function damped(hz, speed = 6) {
let cam = 0;
const dt = 1 / hz;
for (let i = 0; i < hz / 2; i++) cam += (200 - cam) * (1 - Math.exp(-speed * dt));
return cam.toFixed(1);
}
for (const hz of [30, 60, 144]) {
console.log(`${String(hz).padStart(3)} Hz naive ${naive(hz).padStart(5)} damped ${damped(hz)}`);
}clamped: 0 0 300 960 960
30 Hz naive 158.8 damped 190.0
60 Hz naive 191.5 damped 190.0
144 Hz naive 199.9 damped 190.0
The naive version ends in a different place at every frame rate. The damped version ends in the same place every time. The play kit already runs a fixed step, so the naive version would work here, but the damped formula is the one to remember: you'll need it in any engine with a variable time step.
Step 4: a level bigger than the screen
Run to the right. The camera follows with a dead zone and smoothing, and stops at the level's edges. Fall into a pit and you're put back at the start (the next lesson adds proper deaths). Hold G to see the dead zone. The hills in the background move at a third of the camera's speed, a cheap parallax effect that adds depth.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
const T = 16;
const MAP = [
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#.......................####.............................................................#',
'#........................................................................................#',
'#........................................................................................#',
'#.................####........####.......................####............................#',
'#........................................................................................#',
'#........................................................................................#',
'#............####.....................####...........###....................####.........#',
'#........................................................................................#',
'#........................####.................................###........................#',
'#.......####.....................####...........####...................####.......###....#',
'#.............#..........................................................................#',
'#..P..........#..........................................................................#',
'####################....####################....##################....####################',
];
const COLS = MAP[0].length, ROWS = MAP.length, LEVEL_W = COLS * T, LEVEL_H = ROWS * T;
const GRAVITY = 1500, JUMP_SPEED = 440, CUT = 0.45, MAX_FALL = 600;
const RUN_SPEED = 150, ACCEL = 1400, FRICTION = 1800, EPS = 0.001;
const COYOTE_TIME = 0.1, BUFFER_TIME = 0.12;
const DEAD_W = 40, DEAD_H = 40, CAM_SPEED = 6;
const startRow = MAP.findIndex((r) => r.includes('P'));
const start = { x: MAP[startRow].indexOf('P') * T + 2, y: startRow * T };
const player = { x: start.x, y: start.y, w: 12, h: 16, vx: 0, vy: 0, onGround: false, facing: 1 };
const cam = { x: 0, y: LEVEL_H - H, tx: 0, ty: LEVEL_H - H }; // tx/ty: where the camera wants to be
let jumpWasHeld = false, coyote = 0, buffer = 0;
const approach = (v, t, s) => (v < t ? Math.min(v + s, t) : Math.max(v - s, t));
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const jumpHeld = () => keys.has('Space') || keys.has('KeyW') || keys.has('ArrowUp');
const jumpPressed = () => pressed.has('Space') || pressed.has('KeyW') || pressed.has('ArrowUp');
function solidAt(tx, ty) {
if (tx < 0 || tx >= COLS) return true; // side walls
if (ty < 0 || ty >= ROWS) return false; // open sky and bottomless pits
return MAP[ty][tx] === '#';
}
function moveX(b, dx) {
b.x += dx;
const top = Math.floor(b.y / T), bottom = Math.floor((b.y + b.h - EPS) / T);
if (dx > 0) {
const tx = Math.floor((b.x + b.w - EPS) / T);
for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = tx * T - b.w; return 'right'; }
} else if (dx < 0) {
const tx = Math.floor(b.x / T);
for (let ty = top; ty <= bottom; ty++) if (solidAt(tx, ty)) { b.x = (tx + 1) * T; return 'left'; }
}
return null;
}
function moveY(b, dy) {
b.y += dy;
const left = Math.floor(b.x / T), right = Math.floor((b.x + b.w - EPS) / T);
if (dy > 0) {
const ty = Math.floor((b.y + b.h - EPS) / T);
for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = ty * T - b.h; return 'floor'; }
} else if (dy < 0) {
const ty = Math.floor(b.y / T);
for (let tx = left; tx <= right; tx++) if (solidAt(tx, ty)) { b.y = (ty + 1) * T; return 'ceiling'; }
}
return null;
}
function updateCamera(dt) {
// where the camera would be if it centered the player exactly
const fx = player.x + player.w / 2 - W / 2, fy = player.y + player.h / 2 - H / 2;
// dead zone: only move the target when the player leaves the box around it
if (fx > cam.tx + DEAD_W / 2) cam.tx = fx - DEAD_W / 2;
if (fx < cam.tx - DEAD_W / 2) cam.tx = fx + DEAD_W / 2;
if (fy > cam.ty + DEAD_H / 2) cam.ty = fy - DEAD_H / 2;
if (fy < cam.ty - DEAD_H / 2) cam.ty = fy + DEAD_H / 2;
cam.tx = clamp(cam.tx, 0, LEVEL_W - W);
cam.ty = clamp(cam.ty, 0, LEVEL_H - H);
// smoothing, independent of the step size
const k = 1 - Math.exp(-CAM_SPEED * dt);
cam.x += (cam.tx - cam.x) * k;
cam.y += (cam.ty - cam.y) * k;
}
function update(dt) {
const dir = (keys.has('ArrowRight') || keys.has('KeyD') ? 1 : 0) - (keys.has('ArrowLeft') || keys.has('KeyA') ? 1 : 0);
if (dir !== 0) player.facing = dir;
const rate = dir !== 0 ? (player.onGround ? ACCEL : ACCEL * 0.6) : (player.onGround ? FRICTION : 300);
player.vx = approach(player.vx, dir * RUN_SPEED, rate * dt);
if (player.onGround) coyote = COYOTE_TIME; else coyote -= dt;
if (jumpPressed()) buffer = BUFFER_TIME; else buffer -= dt;
if (buffer > 0 && coyote > 0) { player.vy = -JUMP_SPEED; buffer = 0; coyote = 0; }
const held = jumpHeld();
if (jumpWasHeld && !held && player.vy < 0) player.vy *= CUT;
jumpWasHeld = held;
player.vy = Math.min(player.vy + GRAVITY * dt, MAX_FALL);
if (moveX(player, player.vx * dt)) player.vx = 0;
const hit = moveY(player, player.vy * dt);
player.onGround = hit === 'floor';
if (hit) player.vy = 0;
if (player.y > LEVEL_H + 40) { // fell into a pit: back to the start for now
Object.assign(player, { x: start.x, y: start.y, vx: 0, vy: 0 });
}
updateCamera(dt);
}
function drawBackground(camX) {
const sky = ctx.createLinearGradient(0, 0, 0, H);
sky.addColorStop(0, '#1a237e'); sky.addColorStop(1, '#5c6bc0');
ctx.fillStyle = sky; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#3949ab'; // far hills: move at 1/3 of the camera speed
const off = Math.round(camX / 3) % 160;
for (let i = -1; i < 5; i++) {
const x = i * 160 - off;
ctx.beginPath(); ctx.moveTo(x, H); ctx.lineTo(x + 80, 150); ctx.lineTo(x + 160, H); ctx.fill();
}
}
function drawTiles() {
// only the tiles inside the camera (plus one for partial tiles)
const c0 = Math.max(0, Math.floor(cam.x / T)), c1 = Math.min(COLS - 1, Math.floor((cam.x + W) / T));
const r0 = Math.max(0, Math.floor(cam.y / T)), r1 = Math.min(ROWS - 1, Math.floor((cam.y + H) / T));
for (let ty = r0; ty <= r1; ty++) {
for (let tx = c0; tx <= c1; tx++) {
if (MAP[ty][tx] !== '#') continue;
const x = tx * T, y = ty * T;
ctx.fillStyle = '#5b3a29'; ctx.fillRect(x, y, T, T);
ctx.fillStyle = '#6d4a36'; ctx.fillRect(x + 2, y + 2, T - 4, T - 4);
if (ty > 0 && MAP[ty - 1][tx] !== '#') { ctx.fillStyle = '#4caf50'; ctx.fillRect(x, y, T, 3); }
}
}
}
function drawPlayer() {
const x = Math.round(player.x), y = Math.round(player.y);
ctx.fillStyle = '#ffb74d'; ctx.fillRect(x, y, player.w, player.h);
ctx.fillStyle = '#5d4037'; ctx.fillRect(x, y, player.w, 4);
ctx.fillStyle = '#fff';
const ex = player.facing > 0 ? x + 6 : x + 1;
ctx.fillRect(ex, y + 6, 2, 3); ctx.fillRect(ex + 4, y + 6, 2, 3);
}
function draw() {
const camX = Math.round(cam.x), camY = Math.round(cam.y);
drawBackground(camX);
ctx.save();
ctx.translate(-camX, -camY); // world space starts here
drawTiles();
drawPlayer();
ctx.restore(); // back to screen space
if (keys.has('KeyG')) {
ctx.strokeStyle = '#ff0';
ctx.strokeRect(Math.round(W / 2 - DEAD_W / 2 + cam.tx - cam.x) + 0.5, Math.round(H / 2 - DEAD_H / 2 + cam.ty - cam.y) + 0.5, DEAD_W, DEAD_H);
}
ctx.fillStyle = '#e8eaf6'; ctx.font = '11px ui-monospace, monospace'; ctx.textAlign = 'left';
ctx.fillText(`camera ${camX}, ${camY} level ${LEVEL_W}x${LEVEL_H}`, 8, 16);
}
run(update, draw, 'Arrows / A D to run, Space / W / Up to jump, hold G for the dead zone');
</script>The new pieces:
startis read from thePin the map, so moving the spawn point is a level edit, not a code change.solidAttreats the area above and below the map as empty, so pits are bottomless, while the left and right edges stay solid.updateCamerakeeps a target (cam.tx,cam.ty) that only moves when the player leaves the dead zone, clamps the target to the level, and lets the real camera ease toward it.drawTilesdraws only the visible tiles: about 31×18 of the level's 1,980, whatever the level size.
Things to try: set DEAD_W to 0 for a camera that is always centered; set CAM_SPEED to 30 for a tight camera or 2 for a lazy one; add look-ahead by shifting the target player.facing * 40 pixels in the direction the player faces, so they can see more of what's coming.
Test yourself
How does this lesson draw the whole world shifted by the camera?
- It subtracts
cam.xfrom every object's position in update ctx.translate(-cam.x, -cam.y)before drawing world objects, thenctx.restore()before the HUD- It moves the canvas element with CSS
- It redraws the tile map into a new array
Why use 1 - Math.exp(-speed * dt) instead of a fixed 0.1 for camera smoothing?
- It is faster to compute
- It gives the same motion over time regardless of frame rate or step size
- It makes the camera never move
Math.expis required by canvas
The level is 1440 pixels wide and the screen 480. What range is cam.x clamped to?
- 0 to 1440
- 0 to 960
- -240 to 1200
- 480 to 1440