Workshop › Breakout › Step 18 of 39
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
}
```dx and dy are the distances from that point to the center.√(dx² + dy²). Comparing squares gives the same answer without a square root.Write hitsBrick just above function update() {, with an empty line between them.
Skills: Collision detection
← A color for every row Break a brick →