Workshop › Pool › Step 16 of 33

Balls that touch

What we are doing

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

What it means

Your turn

  1. Above function step() { write collide, with an empty line after it.
  2. In step, after the ball loop's closing }, write the pair loop line.

Skills: Collision detection

All steps

  1. The room
  2. The table
  3. The cue ball
  4. Draw the balls
  5. The rack
  6. Numbers on the balls
  7. An aim line
  8. Turn the aim
  9. A shot is a velocity
  10. Roll
  11. Friction
  12. Cushions
  13. Aiming and rolling
  14. Hide the aim while rolling
  15. Count the shots
  16. Balls that touch
  17. Swap the push
  18. Six pockets
  19. In the pocket
  20. Scratch
  21. Balls left
  22. Clear the table
  23. Choose the power
  24. A power bar
  25. A slingshot
  26. Press to aim
  27. Pull back and let go
  28. Smaller steps
  29. Predict the hit
  30. Draw the ghost ball
  31. Where the hit ball goes
  32. Your best
  33. Build it yourself: two players