Workshop › Endless Runner › Step 11 of 19

Crash

What we are doing

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)
  }
```

What it means

Your turn

  1. Under CUT, write MARGIN.
  2. Under spawn, write hits.
  3. At the end of update, write the crash check.
  4. At the end of draw, write the Game Over block.

Skills: Collision detection, Game states

All steps

  1. The ground
  2. The runner
  3. Draw again and again
  4. Gravity
  5. Jump
  6. Short hops
  7. Tap to jump
  8. Things that come at you
  9. Cacti keep coming
  10. Wait for the start
  11. Crash
  12. Try again
  13. Faster and faster
  14. Remember the best run
  15. The score counter
  16. Birds
  17. Which keys are down?
  18. Duck
  19. Build it yourself: jump buffering