Workshop › Pool › Step 29 of 33

Predict the hit

What we are doing

With the physics this precise, we can predict the shot. The ghost ball is where the cue ball will be when it first touches another ball. For each ball: how far along the aim line it is (t), and how far to the side (side, squared). If the side distance is less than 2R, the cue ball will hit it.

```js
// Where the cue ball will first touch another ball along the aim: the "ghost ball".
function ghost() {
  const ux = Math.cos(aim)
  const uy = Math.sin(aim)
  let first = null
  for (const b of balls) {
    if (b === cue) continue
    const dx = b.x - cue.x
    const dy = b.y - cue.y
    const t = dx * ux + dy * uy // how far along the aim line the ball is
    const side = dx * dx + dy * dy - t * t // squared distance from the line
    if (t <= 0 || side >= R * R * 4) continue
    const hit = t - Math.sqrt(R * R * 4 - side)
    if (!first || hit < first.hit) first = { hit, ball: b, x: cue.x + ux * hit, y: cue.y + uy * hit }
  }
  return first
}
```

What it means

Your turn

Above function draw() { write ghost with its comment, and leave an empty line after it.

Skills: Collision detection, Functions

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