Workshop › Zelda-style Dungeon › Step 4 of 22

Walk

What we are doing

Holding an arrow walks the hero that way, 2.5 pixels a frame, and turns it to face that way. DIRS gives each arrow key its direction. Walls don't stop you yet.

```js
const SPEED = 2.5
const DIRS = { ArrowUp: [0, -1], ArrowDown: [0, 1], ArrowLeft: [-1, 0], ArrowRight: [1, 0] }
const held = {}

function move(body, dx, dy) {
  body.x += dx
  body.y += dy
}

document.addEventListener('keydown', (event) => {
  held[event.key] = true
  if (DIRS[event.key]) event.preventDefault()
})
document.addEventListener('keyup', (event) => {
  held[event.key] = false
})

function update() {
  let dir = null
  for (const key in DIRS) if (held[key]) dir = DIRS[key]
  if (dir) {
    player.dir = dir
    move(player, dir[0] * SPEED, dir[1] * SPEED)
  }
}

  update()
```

What it means

Your turn

  1. Under SIZE, write SPEED; under ROWS, write DIRS; under player, write held.
  2. Above draw, write move, the key listeners and update.
  3. In loop, call update() before draw().

Skills: Keyboard and mouse input

All steps

  1. A room
  2. The hero
  3. The game loop
  4. Walk
  5. Walls
  6. A touch pad
  7. Next room
  8. The sword
  9. Enemies
  10. Strike!
  11. They chase you
  12. They wander
  13. Ouch
  14. Blinking and hearts
  15. Keys and hearts
  16. A world that remembers
  17. The locked door
  18. A timer
  19. Game over
  20. The stairs out
  21. Best time
  22. Build it yourself: cleared rooms