Workshop › OutRun-style Racer › Step 23 of 44
On a phone, a finger on the left third of the game steers left, on the right third steers right, and anywhere it also accelerates. We work out which third the finger is in from its position.
```js
// Touch: hold the left or right third to steer; the car accelerates on its own while you touch.
canvas.addEventListener('pointerdown', (event) => {
const rect = canvas.getBoundingClientRect()
const third = ((event.clientX - rect.left) / rect.width) * 3
keys.ArrowUp = true
if (third < 1) keys.ArrowLeft = true
if (third >= 2) keys.ArrowRight = true
})
function stopTouch() {
keys.ArrowUp = keys.ArrowLeft = keys.ArrowRight = false
}
```getBoundingClientRect() gives where the canvas is on the page and how wide it is; event.clientX is where the finger
is.(finger - left edge) / width is 0 to 1; times 3, third is 0 to 3. Below 1 is the left third, 2 or more the right.stopTouch lets go of all three keys at once.Replace the old touch code (from its comment to the end of stopTouch) with the new one. The two lines below it stay.
Skills: Keyboard and mouse input
← The grass is slow A track with curves →