← Beginner path

STEP 4 OF 7

Input controls

A game reacts to input by recording which keys are held, then reading that state in every game-loop update. This keeps movement predictable.

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

function update() {
  if (keys.has('ArrowLeft')) player.x -= player.speed;
}

Next actions: detect collisions · try the playground · see project routes

Before you continue

Direct answer: Record input events as state, then read that state during the game loop so movement stays predictable.

What you need first

The game loop lesson.

After this lesson

You can explain the idea, change the supplied example, and choose the next related lesson.

When to use it

Use keyboard events for desktop controls; add visible touch controls when the game must work on phones.

Common mistake

Moving the player only inside a key event, which makes continuous movement difficult to control.

Try it and check it

This lesson includes its runnable example or code experiment above. Change one value, run it again, and confirm the visible result changes before moving on.

Real game connection

Try the controls in Snake.

Compatibility: Test in a current Chrome, Firefox, Safari, or Edge browser. Canvas and standard input work broadly in current browsers; audio still needs a user action.

Source and update

Reviewed against MDN Web Docs. Updated 2026-07-14. This page does not claim performance results beyond the local example check.