Workshop › Pool › Step 13 of 33

Aiming and rolling

What we are doing

The game has two moods: 'aiming', waiting for a shot, and 'rolling', while anything moves. A shot is only allowed while aiming. When every ball is still again, it is back to aiming.

```js
let state // 'aiming', 'rolling' or 'won'

  state = 'aiming'

function shoot() {
  if (state !== 'aiming') return
  cue.vx = Math.cos(aim) * power
  cue.vy = Math.sin(aim) * power
  state = 'rolling'
}

function update() {
  if (state !== 'rolling') return
  step()
  let moving = false
  for (const b of balls) {
    b.vx *= FRICTION
    b.vy *= FRICTION
    if (Math.hypot(b.vx, b.vy) < 0.05) b.vx = b.vy = 0
    else moving = true
  }
  if (moving) return
  state = 'aiming'
}
```

What it means

Your turn

  1. Under let power write let state ...; in reset, under power = 8, write state = 'aiming'.
  2. In shoot, add the first line and the last line.
  3. In update, add the first line, let moving = false above the loop, else moving = true under the stop line, and the last two lines after the loop.

Skills: Game states

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