Workshop › Pool › Step 16 of 33
Two balls touch when their centres are less than 2R apart. First we only make sure they never overlap: push them apart
along the line between their centres until they just touch. Each pair of balls is checked once per step.
```js
function collide(a, b) {
const dx = b.x - a.x
const dy = b.y - a.y
const dist = Math.hypot(dx, dy)
if (dist >= R * 2 || dist === 0) return
const nx = dx / dist
const ny = dy / dist
// Push them apart so they only just touch.
const overlap = (R * 2 - dist) / 2
a.x -= nx * overlap
a.y -= ny * overlap
b.x += nx * overlap
b.y += ny * overlap
}
for (let i = 0; i < balls.length; i++) for (let j = i + 1; j < balls.length; j++) collide(balls[i], balls[j])
```dist is the distance between the centres. Not touching (or exactly on top of each other, where there is no direction):
nothing to do.(nx, ny) is the direction from a to b with length 1 (the normal).overlap is half of how much they overlap; each ball moves that much away from the other.step, j starts at i + 1, so each pair is checked once and a ball never with itself.function step() { write collide, with an empty line after it.step, after the ball loop's closing }, write the pair loop line.Skills: Collision detection
← Count the shots Swap the push →