130 Widgets

Semi-random thoughts and tales of tinkering

Lesson 4: Keyboard Controls

A game isn't a game until you can control it! In this lesson, you'll learn how to listen for keyboard presses and move your character with W A S D keys — just like in real Minecraft! 🎮

Events: The Browser Talking to Your Code

When you press a key, click the mouse, or scroll the page, the browser creates an event. An event is the browser's way of saying "Hey, something just happened!"

We can tell the browser: "When a key is pressed, run this function." This is called adding an event listener.

// When any key is pressed DOWN, run this function
document.addEventListener('keydown', function(event) {
  console.log('You pressed: ' + event.code);
});

🎧 addEventListener

  • 'keydown' — Fires when a key is pressed down
  • 'keyup' — Fires when a key is released
  • event.code — Tells you WHICH key (like 'KeyA', 'KeyW', 'ArrowUp')

Why We Track Keys With an Object

Here's a problem: if we only move the player inside the keydown event, the player moves once, pauses, then starts repeating (like when you hold a key while typing). That feels terrible in a game!

Instead, we use a clever trick: we keep track of which keys are currently held down using an object, then check it in the game loop.

// An object to track which keys are currently pressed
const keys = {};

// When a key goes DOWN, remember it
document.addEventListener('keydown', function(event) {
  keys[event.code] = true;
});

// When a key comes UP, forget it
document.addEventListener('keyup', function(event) {
  keys[event.code] = false;
});
Think of the keys object like a light switch panel. When you press the "A" key, the "A" switch flips ON. When you let go, it flips OFF. Our game loop checks the switches 60 times per second to see which ones are on!

Moving the Player

Now in our game loop, we check which keys are held down and move the player:

const speed = 4;  // How fast the player moves (pixels per frame)

function gameLoop() {
  ctx.clearRect(0, 0, 600, 400);

  // Check the keys and move the player
  if (keys['KeyA'] || keys['ArrowLeft'])  playerX -= speed;  // Move left
  if (keys['KeyD'] || keys['ArrowRight']) playerX += speed;  // Move right
  if (keys['KeyW'] || keys['ArrowUp'])    playerY -= speed;  // Move up
  if (keys['KeyS'] || keys['ArrowDown'])  playerY += speed;  // Move down

  // Draw the player at the new position
  drawPlayer(playerX, playerY);

  requestAnimationFrame(gameLoop);
}

🔢 Objects: Like a Dictionary

An object in JavaScript is like a dictionary — it stores pairs of names and values. We use keys['KeyA'] to look up whether the A key is pressed:

  • keys['KeyA'] = true → "A is being held down"
  • keys['KeyA'] = false → "A is not being pressed"
  • We use || which means OR — so both WASD and arrow keys work

Try It! Click the Game Below, Then Use WASD to Move

⬆️ Click here first, then use W A S D or Arrow Keys to move!

Keeping the Player On Screen

Right now, the player can walk right off the edge of the screen! We need to add boundaries — limits that stop the player from going too far:

// Keep player inside the canvas
if (playerX < 0) playerX = 0;
if (playerX > canvas.width - 24) playerX = canvas.width - 24;
if (playerY < 0) playerY = 0;
if (playerY > canvas.height - 56) playerY = canvas.height - 56;
Why canvas.width - 24? Because the player is 24 pixels wide! If we just checked playerX > canvas.width, the player's left edge would stop at the right side, but the rest of the character would be off-screen. We subtract the player's width so the right edge of the character stops at the boundary.

Adding Direction (Facing Left or Right)

In Minecraft, your character faces the direction you're walking. We can track which direction the player is facing and flip the drawing:

let facing = 1;  // 1 = right, -1 = left

if (keys['KeyA'] || keys['ArrowLeft']) {
  playerX -= speed;
  facing = -1;  // Now facing left
}
if (keys['KeyD'] || keys['ArrowRight']) {
  playerX += speed;
  facing = 1;   // Now facing right
}

🏆 Challenges — Try These!

  • Change the speed variable to make the player faster or slower
  • Add a speed boost: when the player holds Shift, double the speed! (hint: check keys['ShiftLeft'])
  • Display the player's position on screen using ctx.fillText('X: ' + playerX, 10, 20)
  • Make the ground blocks from Lesson 2 appear at the bottom of the screen
  • Add a second player controlled by I J K L keys!

📝 What We Learned

  • Events are notifications from the browser (key presses, mouse clicks)
  • addEventListener lets us run code when events happen
  • We track held keys in an object and check them in the game loop
  • || means OR — either condition can be true
  • Boundaries keep the player on screen