Workshop › Pac-Man-style Maze Chase › Step 14 of 42
On a phone there are no arrow keys. Remember where a touch went down; when it comes up, the longer side of the movement gives the direction. Tiny movements are ignored, so a tap does not steer by accident.
```js
// Touch: swipe in the direction to go.
let swipeStart = null
canvas.addEventListener('pointerdown', (event) => {
swipeStart = { x: event.clientX, y: event.clientY }
})
canvas.addEventListener('pointerup', (event) => {
if (!swipeStart) return
const dx = event.clientX - swipeStart.x
const dy = event.clientY - swipeStart.y
swipeStart = null
if (Math.max(Math.abs(dx), Math.abs(dy)) < 20) return
if (Math.abs(dx) > Math.abs(dy)) steer([Math.sign(dx), 0])
else steer([0, Math.sign(dy)])
})
```pointerdown / pointerup fire when a finger (or mouse button) goes down and up.dx, dy are how far it moved; Math.abs drops the sign, Math.max takes the bigger.Math.sign(dx) is 1, -1 or 0: exactly a direction number.Under the key listener, leave an empty line and write the touch code.
Skills: Keyboard and mouse input
← Turn back at once Eat the pellets →