Workshop › Scorched Earth-style Artillery › Step 8 of 23
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()
}
```vx, vy is the speed in pixels per frame: the barrel's direction, power pixels long.state is 'flying', so a second Space does nothing.{ } block because more will go in it later.tanks, write turn, shell and state; in reset, set them after the tanks.aimBy, write fire; in the key listener, fire on Space.draw, draw the shell above the readout.Skills: Keyboard and mouse input, Velocity and gravity