Workshop › Zelda-style Dungeon › Step 6 of 22

A touch pad

What we are doing

On a phone, a faint circle in the bottom-left corner is a pad: hold a side of it to walk that way. Whichever is farther from the middle, across or down, decides the direction. (A tap elsewhere will swing the sword, soon.)

```js
// Touch: the pad in the corner moves, a tap anywhere else swings the sword.
const PAD = { x: 70, y: 330, r: 60 }
let padDir = null
canvas.addEventListener('pointerdown', (event) => {
  const rect = canvas.getBoundingClientRect()
  const x = ((event.clientX - rect.left) * canvas.width) / rect.width
  const y = ((event.clientY - rect.top) * canvas.height) / rect.height
  const dx = x - PAD.x
  const dy = y - PAD.y
  if (Math.hypot(dx, dy) < PAD.r) padDir = Math.abs(dx) > Math.abs(dy) ? [Math.sign(dx), 0] : [0, Math.sign(dy)]
})
canvas.addEventListener('pointerup', () => {
  padDir = null
})

  let dir = padDir

  // The touch pad, faint, in the corner.
  ctx.strokeStyle = 'rgba(255, 255, 255, 0.25)'
  ctx.lineWidth = 2
  ctx.beginPath()
  ctx.arc(PAD.x, PAD.y, PAD.r, 0, Math.PI * 2)
  ctx.stroke()
```

What it means

Your turn

  1. Under the key listeners, write the pad and its two listeners.
  2. In update, start dir from padDir.
  3. At the end of draw, draw the pad.

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