TExcelTAD

Keyboard Input

Browsers deliver keys as events (keydown, keyup) at any moment, but a game wants to ask questions once per update: is Left held right now? Was Jump pressed since the last update? This lesson turns events into those answers, then adds action mapping so the game asks about "jump" instead of "Space".

Held keys: a Set

The core is a Set of the keys that are down. keydown adds, keyup removes, and the update function reads it:

js
const keys = new Set();
addEventListener('keydown', (e) => keys.add(e.code));
addEventListener('keyup', (e) => keys.delete(e.code));

function update(dt) {
  if (keys.has('ArrowLeft')) player.x -= player.speed * dt;   // true for as long as the key is held
}

Use e.code (the physical key: KeyW, ArrowLeft, Space, ShiftLeft) for game controls, so WASD stays in the same place on AZERTY or Dvorak keyboards. Use e.key (the character: "w", "z", "?") only for typing text, such as a name entry.

Pressed this update: edge detection

Some actions must happen once per press: jump, shoot a single shot, open the pause menu. Checking keys.has('Space') would jump on every update while the key is held. Two more details make this tricky:

  • If a key is held, the operating system repeats keydown events (with e.repeat === true) after a short delay.
  • A quick tap can go down and up between two updates, so it is never seen as "held".

So record presses in a second set, ignore repeats, and clear that set after each update:

js · try it yourself
// A tiny input model fed with events, to see what update() observes.
class Input {
  held = new Set();
  pressed = new Set();     // went down since the last update
  released = new Set();    // went up since the last update
  keydown(code, repeat = false) {
    if (!repeat) this.pressed.add(code);
    this.held.add(code);
  }
  keyup(code) {
    this.held.delete(code);
    this.released.add(code);
  }
  endUpdate() {            // call after every update()
    this.pressed.clear();
    this.released.clear();
  }
}

const input = new Input();
function update(label) {
  const jump = input.pressed.has('Space') ? 'JUMP' : '-';
  console.log(`${label.padEnd(26)} held=${[...input.held].join(',') || 'none'}  pressed:${jump}`);
  input.endUpdate();
}

input.keydown('Space');               update('Space down');
input.keydown('Space', true);         update('OS auto-repeat');
                                      update('still held');
input.keyup('Space');                 update('Space up');
input.keydown('Space'); input.keyup('Space');
                                      update('tap between two updates');
Space down                 held=Space  pressed:JUMP
OS auto-repeat             held=Space  pressed:-
still held                 held=Space  pressed:-
Space up                   held=none  pressed:-
tap between two updates    held=none  pressed:JUMP

The play kit in every game does exactly this with its keys and pressed sets: pressed is cleared after each update().

Actions instead of keys

Players expect several keys to do the same thing (arrows and WASD, Space and W for jump), and good games let players rebind them. Keep a table from actions to keys, and have game code ask about actions only:

js
const BINDINGS = {
  left:  ['ArrowLeft', 'KeyA'],
  right: ['ArrowRight', 'KeyD'],
  jump:  ['Space', 'ArrowUp', 'KeyW'],
  dash:  ['ShiftLeft', 'KeyX'],
};
const isDown = (action) => BINDINGS[action].some((k) => keys.has(k));
const wasPressed = (action) => BINDINGS[action].some((k) => pressed.has(k));

Rebinding is now just changing an array, and adding a gamepad later only means one more source of the same actions (see Gamepad Input).

Try it

Move with arrows/WASD. Space (or W/Up) jumps once per press: hold it and you still jump only once. Shift or X dashes. The panel on the right shows the raw input state every update.

html · try it yourself
<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 BINDINGS = {
  left: ['ArrowLeft', 'KeyA'], right: ['ArrowRight', 'KeyD'],
  jump: ['Space', 'ArrowUp', 'KeyW'], dash: ['ShiftLeft', 'ShiftRight', 'KeyX'],
};
const isDown = (a) => BINDINGS[a].some((k) => keys.has(k));
const wasPressed = (a) => BINDINGS[a].some((k) => pressed.has(k));

const GROUND = 230;
const p = { x: 100, y: GROUND, vx: 0, vy: 0, dashTime: 0, facing: 1, jumps: 0, dashes: 0 };
let lastPressed = '';

function update(dt) {
  if (pressed.size) lastPressed = [...pressed].join(' ');
  const dir = (isDown('right') ? 1 : 0) - (isDown('left') ? 1 : 0);
  if (dir) p.facing = dir;
  if (wasPressed('jump') && p.y >= GROUND) { p.vy = -380; p.jumps++; }   // once per press
  if (wasPressed('dash') && p.dashTime <= 0) { p.dashTime = 0.15; p.dashes++; }
  p.dashTime -= dt;
  p.vx = p.dashTime > 0 ? p.facing * 520 : dir * 150;
  p.vy += 1000 * dt;
  p.x = Math.max(10, Math.min(300, p.x + p.vx * dt));
  p.y = Math.min(GROUND, p.y + p.vy * dt);
  if (p.y >= GROUND) p.vy = 0;
}

function draw() {
  ctx.fillStyle = '#16213e'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#394867'; ctx.fillRect(0, GROUND + 20, 320, H);
  ctx.fillStyle = p.dashTime > 0 ? '#fff' : '#ff7043';
  ctx.fillRect(Math.round(p.x - 10), Math.round(p.y - 20), 20, 40);
  ctx.fillStyle = '#000';
  ctx.fillRect(Math.round(p.x + p.facing * 4 - 2), Math.round(p.y - 12), 4, 4);     // eye shows facing
  // input panel
  ctx.fillStyle = '#0b0f1c'; ctx.fillRect(330, 0, 150, H);
  ctx.fillStyle = '#cfd8dc'; ctx.font = '12px ui-monospace, monospace'; ctx.textAlign = 'left';
  const lines = ['held keys:', ...([...keys].slice(0, 5)), '', 'last pressed:', lastPressed, '',
    'actions:', ...Object.keys(BINDINGS).map((a) => `${a.padEnd(6)}${isDown(a) ? 'DOWN' : '-'}`),
    '', `jumps ${p.jumps}  dashes ${p.dashes}`];
  lines.forEach((t, i) => ctx.fillText(t, 338, 18 + i * 14));
}

run(update, draw, 'Arrows/WASD move, Space jumps, Shift or X dashes');
</script>

Keyboard gotchas

Problem Fix
The page scrolls while you play preventDefault() on arrow keys and Space (only while the game has focus)
A key "sticks" after clicking away Clear keys on blur and on visibilitychange
Some 3-key combinations don't register Cheap keyboards can't detect certain combinations (ghosting). Choose default bindings that are spread out, and allow rebinding
e.key is "Z" instead of "z" with Shift held, or a different letter on another layout Use e.code for controls
Ctrl+W closes the tab Never bind browser shortcuts (Ctrl+W, Ctrl+T, F5); preventDefault can't block all of them

Tip: Show the controls on screen, in the game itself. Players skip instructions printed under the game.

Test yourself

The player holds Space for one second. With pressed cleared after each update, how many times does pressed.has('Space') return true?

  1. About 60 times
  2. Once, on the first update after the key went down
  3. Never
  4. Once per OS auto-repeat event

Why does the input model also catch a tap that goes down and up between two updates?

  1. Because held remembers it
  2. Because pressed records the press and is only cleared after the next update
  3. Because keyup is delayed by the browser
  4. It doesn't catch it

What is the main benefit of mapping keys to actions such as jump?

  1. It makes the game run faster
  2. Game code asks about actions, so several keys, rebinding and gamepads all work without changing it
  3. Browsers require it
  4. It removes the need for preventDefault