Find a course

Module 5: Input, Collisions and a Full GameLesson 9 of 1112 min

Keyboard Controls

Listen for keydown and keyup events, track held keys for smooth movement, and keep the player inside the screen by clamping positions.

Step 1 of 11Learn

Listening to the keyboard

A game becomes a game when the player can control it. The browser fires a keydown event whenever a key is pressed and a keyup event when it's released. You listen for them on the whole page with document.addEventListener:

document.addEventListener("keydown", function (event) {
  console.log(event.key);
});

The event object describes what happened. Its key property is a string naming the key: "a", "ArrowLeft", "ArrowUp", " " (a single space for the space bar), "Enter" and so on. Open the console, press some keys and watch the names appear; it's the quickest way to find the exact spelling.

Two details catch beginners. First, letter keys are case-sensitive: with Shift or Caps Lock on, the key is "A", not "a". Games often convert with event.key.toLowerCase() before comparing. Second, arrow keys and the space bar normally scroll the page. If your game page is taller than the window, every jump will also scroll it. Calling event.preventDefault() inside the listener stops that default browser behavior for those keys.

Step 2 of 11Practice · Match the pairs

Match each key to the value of event.key it produces.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Left arrow
  2. Space bar
  3. W with Caps Lock off
  4. Escape key
  5. Return key

Step 3 of 11Flashcards

event.key names

Tap a card to flip it.

Step 4 of 11Learn

Smooth movement with held keys

The simplest approach is to move the player inside the keydown listener. Try it and you'll notice a problem: movement is jerky. The player moves once, pauses, then moves repeatedly, because keydown fires on the keyboard's auto-repeat schedule, the same one that repeats a letter when you hold it in a text box. It also can't handle two keys at once well, such as moving and jumping together.

Real games separate input from movement. The listeners only record which keys are currently held, and the game loop moves the player every frame based on that record:

const keys = {};

document.addEventListener("keydown", e => { keys[e.key] = true; });
document.addEventListener("keyup",   e => { keys[e.key] = false; });

function update() {
  if (keys["ArrowLeft"])  player.x -= player.speed;
  if (keys["ArrowRight"]) player.x += player.speed;
}

keys is an object used as a lookup table: keys["ArrowLeft"] is true while the left arrow is held down. Because update runs every frame, the movement is perfectly smooth, and holding two keys works naturally. A speed of 5 pixels per frame moves the player about 300 pixels per second at 60 fps.

Pressing left and right together cancels out here, since both lines run. That's usually exactly what players expect.

Step 5 of 11Diagram

Separate input from movement

Separate input from movementProcess diagram: keydown → keys object → Game loop reads keys → Smooth movement → keyup sets false.keydownkeys objectGame loop readskeysSmooth movementkeyup sets false

Tap a shape with to see more.

keydown

The listener only records: keys[e.key] = true.

keys object

Remembers every key held right now, even two at once.

Game loop reads keys

Every frame: if (keys["ArrowLeft"]) player.x -= speed;

Smooth movement

Moves every frame, not on the keyboard's auto-repeat.

keyup sets false

keys[e.key] = false stops the movement.

Step 6 of 11Practice · True or false

Moving the player directly inside the keydown listener gives the smoothest movement, because keydown fires once per frame.

Step 7 of 11Learn

Keeping the player on screen

Hold the right arrow for a few seconds and the player slides off the edge and disappears. You need to clamp the position: keep it between a minimum and a maximum.

For a player drawn with fillRect, x is the left edge, so the allowed range is from 0 to canvas.width - player.width:

if (player.x < 0) player.x = 0;
if (player.x > canvas.width - player.width) {
  player.x = canvas.width - player.width;
}

This pattern is so common that programmers write a reusable function for it:

function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
}

player.x = clamp(player.x, 0, canvas.width - player.width);

Read it from the inside out: Math.min(max, value) caps the value at the maximum, then Math.max(min, ...) raises it to at least the minimum.

Clamping turns up all over game code: health between 0 and 100, volume between 0 and 1, a camera that shouldn't scroll past the edge of the level. Whenever a number has limits, clamp it right after changing it.

Step 8 of 11Practice · Work it out

The canvas is 480 pixels wide and the player is 32 pixels wide. What is the largest x value the player's top-left corner can have while staying fully on screen?

Step 9 of 11Practice · Diagram

clamp(x, 0, 480 - 32) on a 480-pixel canvas

Where does clamp put a player at x = -12?

Tap the shape that answers the question, then press Check.

clamp(x, 0, 480 - 32) on a 480-pixel canvasScale: x = -12 (too far left), min 0, max 448, x = 500 (too far right).allowed x0100200300400500-12 pxx = -12 (too farleft)0 pxmin 0448 pxmax 448500 pxx = 500 (too farright)
x = -12 (too far left)

Off the left edge.

min 0

Left edge of the canvas.

max 448

480 - 32: the player's right edge touches the wall.

x = 500 (too far right)

Would be off screen.

Step 10 of 11Note

Step 11 of 11Practice · Code challenge

Write clamp(value, min, max) that returns value if it's between min and max, min if it's lower, and max if it's higher. Then write moveLeftRight(x, speed, leftHeld, rightHeld, maxX) that returns the new x after moving left (subtract speed) and/or right (add speed), clamped between 0 and maxX.

Runs in a sandbox in your browser.
  • clamp(50, 0, 100)
  • clamp(-20, 0, 100)
  • clamp(130, 0, 100)
  • moveLeftRight(100, 5, false, true, 448)
  • moveLeftRight(2, 5, true, false, 448)
  • moveLeftRight(200, 5, true, true, 448)