Workshop › Pinball › Step 10 of 42
To stop the ball at a wall we must first know whether it touches one. We find the point of the wall closest to the
ball's centre; if that point is nearer than R, they touch. This works for any slanted line.
```js
// Push the ball out of a segment and bounce it.
function hitSegment(x1, y1, x2, y2, bounce) {
const dx = x2 - x1
const dy = y2 - y1
const t = Math.max(0, Math.min(1, ((ball.x - x1) * dx + (ball.y - y1) * dy) / (dx * dx + dy * dy)))
const px = x1 + t * dx
const py = y1 + t * dy
const d = Math.hypot(ball.x - px, ball.y - py)
if (d >= R || d === 0) return false
return true
}
```dx, dy is the step from one end of the segment to the other.t says where the closest point is: 0 at the start, 1 at the end, 0.5 in the middle. It is the projection of the
ball onto the line (a dot product divided by the length squared), clamped between 0 and 1 with Math.max and
Math.min so the point stays on the segment.(px, py) is that closest point; Math.hypot gives its distance d to the ball's centre.true when d is less than R. bounce (how springy the wall is) is used in two steps.Write the comment and hitSegment above function update() {, with an empty line after it.
Skills: Collision detection, Functions