Workshop › Breakout › Step 18 of 39

Circle meets box

What we are doing

Does the round ball touch a rectangular brick? Find the point of the brick closest to the ball's center; they touch when that point is within one radius.

```js
function hitsBrick(brick) {
  // The point of the brick closest to the ball's center; they touch if it is within one radius.
  const nearestX = clamp(ball.x, brick.x, brick.x + BRICK_W)
  const nearestY = clamp(ball.y, brick.y, brick.y + BRICK_H)
  const dx = ball.x - nearestX
  const dy = ball.y - nearestY
  return dx * dx + dy * dy <= BALL_R * BALL_R
}
```

What it means

Your turn

Write hitsBrick just above function update() {, with an empty line between them.

Skills: Collision detection

All steps

  1. The field and the paddle
  2. Draw again and again
  3. Keep a number inside limits
  4. Follow the mouse
  5. A canvas shown at another size
  6. A ball with a velocity
  7. Draw a round ball
  8. Move the ball
  9. Bounce off the side walls
  10. Bounce off the ceiling
  11. The open floor
  12. Bounce off the paddle
  13. Aim with the paddle
  14. A row of bricks
  15. Draw the bricks
  16. A whole wall: a loop inside a loop
  17. A color for every row
  18. Circle meets box
  19. Break a brick
  20. Hitting the side of a brick
  21. Wait on the paddle
  22. Ride along with the paddle
  23. Launch the ball
  24. Click or press Space
  25. Remember which keys are held
  26. Steer with the arrow keys
  27. Three lives
  28. Lives and a hint on screen
  29. Game over
  30. Keep score
  31. Show the score
  32. Win the game
  33. One function for a new game
  34. Play again
  35. A burst of particles
  36. Break into sparks
  37. Move, fall and disappear
  38. Fade out
  39. Build it yourself: tough bricks