CodeBlanks Logo Icon CodeBlanks

Motion and interaction

JavaScript course · Expert · Lesson 50/63

Move the player with the keydown event and update position in the game loop.

Keyboard input

To move the player with the keyboard we listen for keydown and keyup events. When a key is pressed we set keys[event.key] = true, when released we set keys[event.key] = false. event.key gives the name of the pressed key; for arrow keys we get ArrowLeft, ArrowRight, ArrowUp and ArrowDown.

We bind events with window.addEventListener. Keeping key states in a keys object also supports pressing multiple keys at once.

Updating position

In the draw loop we call an update function each frame. It checks the keys object and changes player.x and player.y based on the arrow keys. For example, if the left arrow is held we slide the player left with player.x -= 4.

The speed value (4 pixels per frame) controls how fast the player moves. We call update inside draw, after drawing.

Exercise Move the player with arrow keys

Define an empty keys object. With window.addEventListener("keydown", ...) set keys[event.key] = true on press, and with window.addEventListener("keyup", ...) set keys[event.key] = false on release. Then add an update function: if ArrowLeft is held do player.x -= 4, if ArrowRight is held do player.x += 4, if ArrowUp is held do player.y -= 4, if ArrowDown is held do player.y += 4. Finally add an update() call at the end of the draw function.

Show example solution
const keys = {};

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

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

// add update(); at the end of the draw function

Test yourself

  1. Which event fires when a key is pressed down?

    • click
    • keydown
    • submit
    • load
    Show answer

    keydown — Correct! keydown fires the moment a key is pressed.

  2. Listen for the keydown event

    window.addEventListener(____, (event) => { keys[event.key] = true; });
    Show answer
    window.addEventListener("keydown", (event) => { keys[event.key] = true; });
  3. Match the event concepts

    keydown
    Key pressed
    keyup
    Key released
    addEventListener
    Listen for event
    event.key
    Pressed key

All lessons in Expert