Workshop › Pool › Step 17 of 33

Swap the push

What we are doing

The heart of the game. Split each velocity into a part along the normal and a part across it. When two balls of the same mass collide, they simply swap the parts along the normal; the parts across stay as they were.

```js
// Two balls of the same mass that touch swap the parts of their velocities that point along the line between them.

  const along = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny
  if (along <= 0) return // already moving apart
  a.vx -= along * nx
  a.vy -= along * ny
  b.vx += along * nx
  b.vy += along * ny
```

What it means

Your turn

  1. Put the comment above function collide(a, b) {.
  2. At the end of collide, under b.y += ny * overlap, write the six lines.

Skills: Velocity and gravity, 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