Workshop › Bomberman-style Arena › Step 38 of 42
On a phone there are no arrow keys, but there is a natural control: put your finger on the side of the player you
want to go. touch compares the finger with the player's center and answers with an arrow key's name, or null when
the finger is on the player.
```js
// Touch: hold a finger on one side of the player to walk that way; tap on the player to drop a bomb.
function touch(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 - (player.x * TILE + TILE / 2)
const dy = y - (TOP + player.y * TILE + TILE / 2)
if (Math.abs(dx) < TILE / 2 && Math.abs(dy) < TILE / 2) return null
if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? 'ArrowRight' : 'ArrowLeft'
return dy > 0 ? 'ArrowDown' : 'ArrowUp'
}
```getBoundingClientRect() tells where the canvas is on the page and how big it is shown; the first lines turn the
pointer's page position into canvas pixels.dx, dy is how far the finger is from the player's center.null. Otherwise the bigger of |dx| and |dy| picks the axis, and its sign the
direction.Above function drawCircle( write the comment and touch.
Skills: Keyboard and mouse input
← Show the powers Play with a finger →