Workshop › Asteroids › Step 12 of 41

Making a bullet

What we are doing

Many bullets can fly at once, so they go in an array. shoot adds one at the ship's nose. Its velocity is the direction times BULLET_SPEED, plus the ship's own velocity, like a ball thrown from a moving car.

```js
const BULLET_SPEED = 7
const BULLET_LIFE = 55 // frames

let bullets

function shoot() {
  const dx = Math.cos(ship.angle)
  const dy = Math.sin(ship.angle)
  bullets.push({
    x: ship.x + dx * SHIP_R,
    y: ship.y + dy * SHIP_R,
    vx: ship.vx + dx * BULLET_SPEED,
    vy: ship.vy + dy * BULLET_SPEED,
    life: BULLET_LIFE,
  })
}

bullets = []
```

What it means

Your turn

  1. Under MAX_SPEED write the two bullet constants; under let ship write let bullets.
  2. Above the keydown listener write shoot, followed by an empty line.
  3. At the bottom, above resetShip(), write bullets = [].

Skills: Arrays and objects, Velocity and gravity

All steps

  1. Black space
  2. Where the ship is
  3. Which way it points
  4. A triangle ship
  5. Which keys are down?
  6. Turning
  7. The game loop
  8. Thrust and drift
  9. A little friction
  10. A speed limit
  11. Around the screen
  12. Making a bullet
  13. Fire!
  14. Bullets fly
  15. A lifetime for bullets
  16. Making a rock
  17. Four big rocks
  18. Drawing the rocks
  19. Jagged rocks
  20. Drifting rocks
  21. When do two circles touch?
  22. Breaking a rock
  23. Bullets hit rocks
  24. Points
  25. Show the score
  26. Losing a life
  27. A rock hits the ship
  28. Show the lives
  29. What time is it?
  30. A moment of safety
  31. Blink while safe
  32. Waves of rocks
  33. The next wave
  34. Faster every wave
  35. One function to start
  36. Playing or over
  37. Game over
  38. Best score
  39. GAME OVER
  40. Play again
  41. Build it yourself: hyperspace