Workshop › Endless Runner › Step 11 of 19
Touching a cactus ends the run. Two boxes overlap when each one starts before the other one ends, on both axes. The boxes are shrunk by 6 pixels so a brush against a corner does not count: it feels fair.
```js
const MARGIN = 6 // forgiving hitboxes: shrink both boxes by this much
function hits(o) {
return (
runner.x + MARGIN < o.x + o.w &&
runner.x + runner.w - MARGIN > o.x &&
runner.y + MARGIN < o.y + o.h &&
runner.y + runner.h - MARGIN > o.y
)
}
if (obstacles.some(hits)) {
state = 'over'
}
if (state === 'over') {
ctx.font = 'bold 28px sans-serif'
ctx.fillText('Game Over', canvas.width / 2, canvas.height / 2)
ctx.font = '16px sans-serif'
ctx.fillText('Press Space to try again', canvas.width / 2, canvas.height / 2 + 28)
}
```MARGIN makes the runner's box 6 pixels smaller on each side before comparing.some(hits) is true if any obstacle hits; then the run is over (and update stops, because the state is no longer
'running').CUT, write MARGIN.spawn, write hits.update, write the crash check.draw, write the Game Over block.Skills: Collision detection, Game states
← Wait for the start Try again →