Semi-random thoughts and tales of tinkering
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! 🎮
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);
});
'keydown' — Fires when a key is pressed down'keyup' — Fires when a key is releasedevent.code — Tells you WHICH key (like 'KeyA', 'KeyW', 'ArrowUp')
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;
});
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!
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);
}
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"|| which means OR — so both WASD and arrow keys work⬆️ Click here first, then use W A S D or Arrow Keys to move!
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;
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.
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
}
speed variable to make the player faster or slowerkeys['ShiftLeft'])ctx.fillText('X: ' + playerX, 10, 20)addEventListener lets us run code when events happen|| means OR — either condition can be true