Web Games From Zero · Episode 01

The Game Loop & Input

The Game Loop & Input is Episode 01 of Web Games From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 01 · Web Games From Zero

A loop plus input is a game. That's not a simplification for beginners — it's the literal truth at the bottom of every title you've ever played, from Pong to the thing with the photoreal puddles. Sixty times a second a game asks two questions: what just happened? (read the controls, move the world) and what does it look like? (draw it). Wire those two questions into a loop that runs at a steady beat and you have the engine that everything else bolts onto.

The demo below is already alive — a little box is wandering the field on its own, because every demo in this series plays itself until you grab the controls. Press WASD or the arrow keys (or click) and it's yours. The promise of this episode is twofold: a player you steer, and a loop so steady that the game behaves identically whether your screen refreshes 30, 60, or 144 times a second. That second part is the single most important habit in game programming, and almost every hobby game gets it wrong. We're getting it right on day one.

0 fps · 0 steps
▶ playing demo — press any key or click to take over
canvas 2D · 0 deps
A box moved by a variable dt. Drag the sim-rate slider — watch the motion change with the frame rate.

Six stages, one little game. They walk from the naive loop everyone writes first, through the fixed-timestep loop everyone should write, into input, the attract-mode pattern, pointer targets, and finally a HUD that shows the loop catching up after a deliberate hitch. Step through them in the stage dropdown as you read.

What you're looking at

The field is the same in every stage: a dark arena, a glowing box (the "player"), and a faint grid so you can see motion. The top-left readout is the HUD: real frames per second, and how many fixed simulation steps the loop ran on the last frame. The top-right panel picks the stage and lets you fake a slow or fast display with the sim rate slider — this is how we'll prove the difference between a variable and a fixed timestep without making you go buy a 144 Hz monitor.

The bottom-left badge tells you the current mode (demo vs you-driving, or the loop's state), and the bottom-right line describes the stage. While nobody has touched the controls, the box drives itself — that's attract mode, and the hint in the center says so. The instant you press a key or click, takeOver() fires, the hint vanishes, and the same movement code that the demo-AI was feeding now reads your keys instead. Let's take the stages one at a time, because each one is a real concept you'll reuse in every game you ever write.

Stage 1 — The bare loop (variable dt)

This is the loop every single person writes first, and it looks reasonable: ask the browser for a frame with requestAnimationFrame, measure how long since the last frame (dt), move the box by speed * dt, draw, repeat. Multiplying by dt feels correct — "move proportional to elapsed time" — and on your machine, at a steady 60 fps, it looks fine.

Now drag the sim rate slider down to 15 Hz and back up to 144. The box's motion gets jittery and uneven as the simulated frame time wobbles. The deeper problem you can't see in ten seconds: any physics richer than constant velocity — gravity, friction, bouncing — produces different results at different frame rates, because errors accumulate per frame and a slow machine takes bigger, coarser steps. A jump that clears a gap at 60 fps falls short at 30. That's a frame-rate-dependent game, and it's a bug, even though it "runs."

Stage 2 — Fixed timestep (the accumulator)

The fix is the heart of this whole series. Don't move the world by however long the last frame took. Instead, accumulate real elapsed time in a bucket and spend it in fixed, constant-size slices — say 1/60th of a second each. If a frame took long enough to fill the bucket three times, you run three identical update steps. If it didn't fill it at all, you run zero and draw again. The simulation always advances in the same quantum, so it is deterministic: identical at any frame rate.

Drag the sim-rate slider in this stage. Watch the steps number in the HUD change — at low Hz the loop runs several catch-up steps per frame; at high Hz it sometimes runs zero — but the box covers the same ground at the same real-world speed regardless. That invariance is the whole point. This is the loop we use for the rest of the season.

Stage 3 — Input (WASD / arrows)

A loop that only animates is a screensaver. Add input and it's a game. We keep a Set of currently-held key codes, updated on keydown and keyup, and inside the update step we turn those keys into a movement vector. Map both the arrow keys and WASD so lefties and righties are both happy. Press the keys now: the box accelerates in the direction you hold and coasts to a stop when you let go (that coast is just friction applied every fixed step — deterministic, because of Stage 2).

Notice the page doesn't scroll when you tap the arrow keys over the demo, but it does scroll normally elsewhere. That's because we call preventDefault() only for the specific keys the game uses, never for the whole keyboard. A game that eats every keystroke is a hostile web citizen.

Stage 4 — Attract mode (the demo plays itself)

Here's the pattern that makes every demo in this series alive on first paint, and it's worth stealing for your own game's title screen. A flag demoMode starts true. A function demoAI() produces the exact same shape of input a human would — a little "controller" object with left/right/up/down and an aim point. The update step doesn't know or care whether that controller came from the AI or from your fingers; it just consumes it. So the demo and the human drive literally the same code path.

The AI here is deliberately simple: it picks a random wander target, seeks it, and when it gets close picks a new one. It doesn't need to be good — it just needs to look alive and exercise the mechanic. The first real key or click calls takeOver(), which flips demoMode off and hides the hint. Toggle the attract checkbox to hand control back to the AI and watch it resume.

Stage 5 — Mouse / touch target

Pointers are the third input device, and on the web one event family — pointer* — covers mouse, trackpad, pen, and touch at once. Click or tap anywhere in the field: the box turns and steers toward where you pressed. We translate the pointer's screen position into canvas coordinates (accounting for the canvas's CSS size versus its backing-store size and the device pixel ratio), store it as a target, and the update step seeks it — the same "seek a point" routine the demo-AI uses for its wander targets. One movement brain, three ways to feed it.

Stage 6 — The loop HUD + a forced hitch

This stage exists to show you the loop surviving a disaster. Every couple of seconds we deliberately stall the loop for a long beat — the kind of pause you get when the browser garbage-collects, the tab was backgrounded, or a giant level finishes loading. Watch the steps counter spike as the accumulator empties out in one frame: the simulation catches up, running many fixed updates at once so no game time is lost, and the box teleports forward to where it should be rather than freezing.

Crucially, the steps number spikes but stays bounded. That's because we clamp the raw dt before adding it to the accumulator. Without that clamp, a five-second pause would queue 300 update steps, which take longer than a frame to run, which makes the next dt even bigger, which queues even more steps — the famous spiral of death that locks up the page. One if statement prevents it.

How the code works

Everything above is maybe 200 lines of vanilla JavaScript and a 2D canvas — zero dependencies, no engine. Here are the four pieces that matter; the rest is drawing.

1 · The fixed-timestep accumulator loop

This is the spine. Measure real time, clamp it, pour it into the accumulator, drain the accumulator in constant STEP-sized updates, then render once. The render(alpha) argument is the fractional leftover in the bucket — Exercise 1 uses it to interpolate for buttery-smooth motion, but you can ignore it at first.

const STEP = 1 / 60;            // fixed simulation step, in seconds
let acc = 0, last = performance.now();

function frame(now) {
  let dt = (now - last) / 1000; last = now;
  if (dt > 0.25) dt = 0.25;     // CLAMP: kills the spiral of death
  acc += dt;

  let steps = 0;
  while (acc >= STEP) {        // run 0..n fixed updates to use up real time
    update(STEP);              // ALWAYS the constant step — never `dt`
    acc -= STEP;
    if (++steps > 8) { acc = 0; break; } // extra belt-and-suspenders cap
  }

  render(acc / STEP);          // alpha in 0..1 for optional interpolation
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

The one rule that makes it all work: update(STEP) does every bit of movement with the constant STEP, never with a variable dt. Burn that in. (Stage 1's "bare loop" deliberately breaks this rule so you can feel the difference; every other stage obeys it.)

2 · Keyboard as a Set, pointer as an object

Input is just state we keep up to date between frames. A Set of held key codes, and a small object for the pointer. Note the two safety habits baked in: preventDefault only on keys the game claims, and clearing all keys on blur so nothing "sticks" when the window loses focus.

const keys = new Set();
const GAME_KEYS = new Set([
  'ArrowUp','ArrowDown','ArrowLeft','ArrowRight',
  'KeyW','KeyA','KeyS','KeyD',
]);

addEventListener('keydown', e => {
  keys.add(e.code);
  takeOver();                          // any key leaves attract mode
  if (GAME_KEYS.has(e.code)) e.preventDefault(); // game keys only — page still scrolls
});
addEventListener('keyup', e => keys.delete(e.code));
addEventListener('blur', () => keys.clear());      // no sticky keys on focus loss

const pointer = { x: 0, y: 0, down: false };
canvas.addEventListener('pointerdown', e => {
  pointer.down = true; takeOver(); setTarget(e);
});
canvas.addEventListener('pointermove', e => { if (pointer.down) setTarget(e); });
addEventListener('pointerup', () => pointer.down = false);

function setTarget(e) {                     // screen px → canvas px (DPR-aware)
  const r = canvas.getBoundingClientRect();
  pointer.x = (e.clientX - r.left) * (canvas.width  / r.width)  / DPR;
  pointer.y = (e.clientY - r.top ) * (canvas.height / r.height) / DPR;
}

3 · One input path for AI and human

This is the attract-mode trick. readInput() returns a controller object. In demo mode it comes from demoAI(); otherwise it's built from the live keys and pointer. The update step calls readInput() and never has to know which is which — so the AI exercises the identical movement code your fingers will.

let demoMode = true;
function takeOver() {
  if (demoMode) { demoMode = false; hint.style.display = 'none'; }
}

function readInput() {
  if (demoMode) return demoAI();          // {dx, dy} aim vector toward a goal
  const left  = keys.has('ArrowLeft')  || keys.has('KeyA');
  const right = keys.has('ArrowRight') || keys.has('KeyD');
  const up    = keys.has('ArrowUp')    || keys.has('KeyW');
  const down  = keys.has('ArrowDown')  || keys.has('KeyS');
  let dx = (right - left), dy = (down - up);          // booleans → -1/0/1
  if (pointer.down) {                                  // pointer overrides: seek it
    dx = pointer.x - player.x; dy = pointer.y - player.y;
  }
  return { dx, dy };
}

function demoAI() {                                   // wander: seek a goal, repick when close
  let dx = goal.x - player.x, dy = goal.y - player.y;
  if (dx*dx + dy*dy < 36*36) pickNewGoal();
  return { dx, dy };
}

4 · update(STEP): movement on the constant step

Finally, the simulation itself. It reads the controller, normalizes the aim into an acceleration, integrates velocity and position using STEP (not dt!), applies friction, and keeps the box inside the arena. Because every term uses the same constant slice, the result is bit-for-bit identical at any frame rate — which is exactly what we proved with the slider back in Stage 2.

const ACCEL = 1400, FRICTION = 6, MAXV = 340;

function update(STEP) {
  const { dx, dy } = readInput();
  const len = Math.hypot(dx, dy) || 1;        // avoid /0; normalize the aim
  player.vx += (dx / len) * ACCEL * STEP;       // a = F; v += a·dt, dt === STEP
  player.vy += (dy / len) * ACCEL * STEP;

  player.vx -= player.vx * FRICTION * STEP;     // exponential-ish drag, per fixed step
  player.vy -= player.vy * FRICTION * STEP;

  const sp = Math.hypot(player.vx, player.vy);  // clamp to a top speed
  if (sp > MAXV) { player.vx *= MAXV/sp; player.vy *= MAXV/sp; }

  player.px = player.x; player.py = player.y;   // stash prev pos for render interpolation
  player.x += player.vx * STEP;
  player.y += player.vy * STEP;

  player.x = Math.max(R, Math.min(W - R, player.x));  // keep inside the arena
  player.y = Math.max(R, Math.min(H - R, player.y));
}

That's the entire engine: a clamped accumulator loop, two input collectors, one AI-or-human input function, and an update that only ever uses STEP. Every later episode — sprites, collisions, jumping, juice — is new code inside these four shapes. Get them in your fingers now.

Common pitfalls

  • Frame-rate-dependent physics. Multiplying movement by a variable dt (Stage 1) means the game runs differently at 30, 60, and 144 Hz — jumps fall short, friction bites harder, replays desync. Move everything inside update(STEP) with the constant step instead. This is the bug this whole episode exists to inoculate you against.
  • The spiral of death. If you don't clamp dt before filling the accumulator, one long pause (tab in background, GC, a big load) queues hundreds of catch-up steps, which take longer than a frame, which makes the next gap bigger — and the page locks up forever. The single line if (dt > 0.25) dt = 0.25; prevents it. (We add a per-frame step cap too, as a second net.)
  • Eating the whole keyboard. Calling preventDefault() on every keydown stops the user from scrolling, tabbing, or using browser shortcuts while your game is on the page. Only preventDefault the keys the game actually uses (GAME_KEYS), so the page behaves normally otherwise.
  • Sticky keys on blur. If the player holds a key and then alt-tabs away, the browser may never deliver the keyup — so the box runs into a wall forever when they come back. Clear the whole keys set on the window blur event.
  • Reading input outside the step. Sample readInput() inside update(STEP), not once per rendered frame. Otherwise on a frame that runs three catch-up steps, all three steps see the same stale input and the determinism you fought for quietly leaks away.

Exercises

  1. Interpolate with the render alpha. The loop already stashes the previous position (player.px/py) and passes alpha = acc / STEP to render. Draw the box at px + (x - px) * alpha instead of at x. At low sim rates the motion goes from steppy to glass-smooth, with the physics still running on the fixed step. This is how real engines decouple a 60 Hz simulation from a 144 Hz display.
  2. Add a second player on different keys. Make a second box driven by IJKL (or the numpad), with its own velocity and its own entry in GAME_KEYS. You'll feel why keeping input as a Set of codes — rather than a single "current key" — matters: two players can hold keys at the same time with zero extra work.
  3. Log update-vs-render counts. Add two counters: bump one each time update() runs and one each time render() runs, and print the running totals to the console once a second. Drag the sim-rate slider and watch the ratio shift — concrete proof that updates and frames are decoupled, and a sanity check you'll reach for whenever a game "feels" frame-rate-bound.

What's next

Episode 02 — Sprites & Animation. Our hero is currently a glowing rectangle with excellent reflexes and no personality. Next we give it a body: load a sprite sheet, flip between frames on a timer driven by this very loop, face the direction it's moving, and squash-and-stretch it as it accelerates. Same engine, suddenly a character.