Workshop › Scorched Earth-style Artillery › Step 8 of 23

Fire!

What we are doing

Space fires a shell from the end of the barrel. It gets a speed: the barrel's direction times the power. state tells what is happening, turn whose shot it is (0 is you). The shell is drawn as a small dark ball; flying comes next.

```js
let turn // 0 or 1: whose shot it is
let shell // { x, y, vx, vy } or null
let state // 'aiming', 'flying', 'boom', 'won' or 'lost'

  turn = 0
  shell = null
  state = 'aiming'

function fire() {
  if (state !== 'aiming') return
  const t = tanks[turn]
  // The shell leaves from the end of the barrel.
  shell = {
    x: t.x + Math.cos(t.angle) * 14,
    y: t.y - 8 + Math.sin(t.angle) * 14,
    vx: Math.cos(t.angle) * t.power,
    vy: Math.sin(t.angle) * t.power,
  }
  state = 'flying'
}

  else if (event.key === ' ') {
    fire()
  } else return

  if (shell) {
    ctx.fillStyle = '#0f172a'
    ctx.beginPath()
    ctx.arc(shell.x, shell.y, 3, 0, Math.PI * 2)
    ctx.fill()
  }
```

What it means

Your turn

  1. Under tanks, write turn, shell and state; in reset, set them after the tanks.
  2. Above aimBy, write fire; in the key listener, fire on Space.
  3. In draw, draw the shell above the readout.

Skills: Keyboard and mouse input, Velocity and gravity

All steps

  1. The ground
  2. Hills
  3. Two tanks
  4. The barrel
  5. The game loop
  6. Aim
  7. Angle and power
  8. Fire!
  9. Flight
  10. Boom
  11. Craters
  12. Falling tanks
  13. Damage
  14. Taking turns
  15. The computer's shot
  16. Hitting a tank
  17. Win or lose
  18. Wind
  19. The computer aims
  20. Aim with the mouse
  21. Drag and let go
  22. The atan2 trap
  23. Build it yourself: a trail