Workshop › Pac-Man-style Maze Chase › Step 11 of 42
An arrow key does not change dir directly: it sets want. At the next tile center, choosePlayer turns to want
if that way is open, otherwise keeps going (or stops at a wall). So a turn pressed a little before a corner happens
exactly at the corner: input buffering, a big part of why maze games feel good.
```js
// Checked in this order, so ties go to up, then left, then down.
const DIRECTIONS = { ArrowUp: [0, -1], ArrowLeft: [-1, 0], ArrowDown: [0, 1], ArrowRight: [1, 0] }
function choosePlayer(p) {
// The wanted direction is remembered, so a turn pressed early happens at the next corner.
if (!same(p.want, STOP) && canGo(p, p.want)) p.dir = p.want
else if (!canGo(p, p.dir)) p.dir = STOP
}
function steer(dir) {
player.want = dir
}
document.addEventListener('keydown', (event) => {
const dir = DIRECTIONS[event.key]
if (dir) {
event.preventDefault()
steer(dir)
}
})
```DIRECTIONS maps each arrow key's name to its [dx, dy]; DIRECTIONS[event.key] is undefined for other keys.choosePlayer: turn to want if one is wanted and it is open; else if the current way is blocked, stop.steer records the wish. preventDefault() stops the arrow keys from also scrolling the page.STOP, write the comment and DIRECTIONS.choosePlayer, and under it write steer and the key listener.Skills: Keyboard and mouse input
← Move every frame Glide between tiles →