TExcelTAD
Home › 2D Games with JavaScript & Canvas › Shooter 2: Projectiles & Cooldowns

Shooter 2: Projectiles & Cooldowns

A ship that can only aim isn't much of a shooter. In this step the ship fires projectiles: small objects that are created at the gun, fly in a straight line and disappear after a while. You'll also add a cooldown, the minimum time between two shots, which decides how the weapon feels more than anything else.

A bullet is just data

Every bullet needs a position, a velocity and a lifetime. Velocity comes from the aim angle: cos gives the x part and sin the y part of a vector of length 1, and multiplying by the bullet speed gives pixels per second.

js
function fire() {
  const muzzle = 14;                                   // spawn at the tip of the barrel
  const cos = Math.cos(player.angle), sin = Math.sin(player.angle);
  bullets.push({
    x: player.x + cos * muzzle,
    y: player.y + sin * muzzle,
    vx: cos * BULLET_SPEED,
    vy: sin * BULLET_SPEED,
    life: BULLET_LIFE,                                 // seconds left before it disappears
  });
}

Each update moves every bullet by velocity × dt and subtracts dt from its life. A bullet is removed when its life runs out or it leaves the screen. Without the lifetime, a bullet that never hits anything would live forever, and the array would grow until the game slows down.

Removing items while looping

Removing elements from an array while you loop over it forwards skips elements: after splice(i, 1) the next bullet moves into index i, and i++ jumps over it. Three safe patterns:

Pattern Code When
Loop backwards for (let i = a.length - 1; i >= 0; i--) if (dead) a.splice(i, 1); simple, few removals
Rebuild bullets = bullets.filter((b) => b.life > 0); clear and short, but creates a new array every frame
Swap-remove a[i] = a[a.length - 1]; a.pop(); (backwards loop) order doesn't matter, fastest

This step uses the backwards loop. In Shooter 4 you'll switch to swap-remove.

Cooldowns

The fire button is held, so the game would fire 60 bullets per second (one per update) without a limit. A cooldown timer counts down by dt; you may fire only when it reaches zero, and firing resets it. There's a subtle detail in how you reset it:

js · try it yourself
const DT = 1 / 60;
const DELAY = 0.15;              // wanted: one shot every 0.15 s = 6.67 shots per second

function simulate(carry) {
  let timer = 0;
  const shots = [];
  for (let frame = 0; frame < 120; frame++) {      // fire held for 2 seconds
    timer -= DT;
    if (timer <= 0) {
      shots.push(frame);
      timer = carry ? timer + DELAY : DELAY;       // carry the leftover time, or throw it away
    }
  }
  return shots;
}

for (const carry of [false, true]) {
  const shots = simulate(carry);
  console.log(carry ? 'timer += DELAY:' : 'timer = DELAY: ', shots.length, 'shots in 2 s, first frames', shots.slice(0, 6).join(' '));
}
timer = DELAY:  12 shots in 2 s, first frames 0 10 20 30 40 50
timer += DELAY: 14 shots in 2 s, first frames 0 9 18 27 36 45

With timer = DELAY, the time left over in the frame where the timer crossed zero is thrown away. Here 0.15 s is exactly 9 frames, but after nine subtractions of 1 / 60 floating-point rounding leaves the timer a hair above zero, so every gap becomes 10 frames: the weapon fires 10% slower than designed. With timer += DELAY, the leftover (positive or negative) is carried into the next gap, so the shots land every 9 frames and the long-run rate is right. With a delay that isn't a whole number of frames, such as 0.12 s (7.2 frames), the carried version alternates between 7- and 8-frame gaps, which nobody can see, and still averages exactly 0.12 s.

Tip: When the button is not held, clamp the timer at zero (timer = Math.max(timer - dt, 0)). Otherwise the timer drifts far below zero while idle, and the next press would fire a burst of several shots in one frame.

Step 2: firing bullets

Hold Space or the left mouse button to fire. The HUD shows how many bullets exist right now: watch it rise and fall as bullets expire.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const BULLET_SPEED = 360, BULLET_LIFE = 0.9, FIRE_DELAY = 0.12;
const player = { x: W / 2, y: H / 2, r: 11, speed: 140, angle: 0 };
const mouse = { x: W / 2 + 80, y: H / 2, down: false };
let bullets = [];
let fireTimer = 0;

cv.addEventListener('pointermove', (e) => {
  const r = cv.getBoundingClientRect();
  mouse.x = (e.clientX - r.left) * W / r.width;
  mouse.y = (e.clientY - r.top) * H / r.height;
});
cv.addEventListener('pointerdown', (e) => { if (e.button === 0) mouse.down = true; });
addEventListener('pointerup', () => { mouse.down = false; });
cv.addEventListener('blur', () => { mouse.down = false; });

const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

function fire() {
  const muzzle = 14;
  const cos = Math.cos(player.angle), sin = Math.sin(player.angle);
  bullets.push({ x: player.x + cos * muzzle, y: player.y + sin * muzzle,
                 vx: cos * BULLET_SPEED, vy: sin * BULLET_SPEED, life: BULLET_LIFE });
}

function update(dt) {
  // movement and aim (step 1)
  let dx = 0, dy = 0;
  if (keys.has('KeyA') || keys.has('ArrowLeft')) dx -= 1;
  if (keys.has('KeyD') || keys.has('ArrowRight')) dx += 1;
  if (keys.has('KeyW') || keys.has('ArrowUp')) dy -= 1;
  if (keys.has('KeyS') || keys.has('ArrowDown')) dy += 1;
  const len = Math.hypot(dx, dy);
  if (len > 0) { dx /= len; dy /= len; }
  player.x = clamp(player.x + dx * player.speed * dt, player.r, W - player.r);
  player.y = clamp(player.y + dy * player.speed * dt, player.r, H - player.r);
  player.angle = Math.atan2(mouse.y - player.y, mouse.x - player.x);

  // shooting with a cooldown
  const wantFire = mouse.down || keys.has('Space');
  if (wantFire) {
    fireTimer -= dt;
    if (fireTimer <= 0) { fire(); fireTimer += FIRE_DELAY; }
  } else {
    fireTimer = Math.max(fireTimer - dt, 0);
  }

  // move bullets, remove dead ones (loop backwards so splice is safe)
  for (let i = bullets.length - 1; i >= 0; i--) {
    const b = bullets[i];
    b.x += b.vx * dt;
    b.y += b.vy * dt;
    b.life -= dt;
    const off = b.x < -10 || b.x > W + 10 || b.y < -10 || b.y > H + 10;
    if (b.life <= 0 || off) bullets.splice(i, 1);
  }
}

function drawShip(x, y, angle) {
  ctx.save();
  ctx.translate(Math.round(x), Math.round(y));
  ctx.rotate(angle);
  ctx.fillStyle = '#4dd0e1';
  ctx.beginPath();
  ctx.moveTo(14, 0); ctx.lineTo(-9, -9); ctx.lineTo(-5, 0); ctx.lineTo(-9, 9);
  ctx.closePath();
  ctx.fill();
  ctx.fillStyle = '#e0f7fa';
  ctx.fillRect(2, -2, 10, 4);
  ctx.restore();
}

function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  ctx.strokeStyle = '#1b2030';
  for (let x = 0; x <= W; x += 30) { ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke(); }
  for (let y = 0; y <= H; y += 30) { ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(W, y + 0.5); ctx.stroke(); }
  ctx.fillStyle = '#ffee58';
  for (const b of bullets) {
    ctx.globalAlpha = Math.min(1, b.life * 4);    // fade out in the last quarter second
    ctx.fillRect(Math.round(b.x) - 2, Math.round(b.y) - 2, 4, 4);
  }
  ctx.globalAlpha = 1;
  drawShip(player.x, player.y, player.angle);
  ctx.strokeStyle = '#ff5252';
  const mx = Math.round(mouse.x), my = Math.round(mouse.y);
  ctx.beginPath(); ctx.arc(mx, my, 6, 0, Math.PI * 2); ctx.stroke();
  ctx.fillStyle = '#9aa4c0'; ctx.font = '12px system-ui, sans-serif'; ctx.textAlign = 'left';
  ctx.fillText(`bullets: ${bullets.length}`, 8, 16);
}

run(update, draw, 'WASD to move, mouse to aim, hold Space or click to fire');
</script>

Things to try in the playground:

  • Set FIRE_DELAY to 0.04 for a machine gun, or 0.5 with BULLET_SPEED = 600 for a heavy cannon. The same code gives very different weapons.
  • Add spread: const a = player.angle + (Math.random() - 0.5) * 0.2; and use a in fire(). A little inaccuracy makes fast weapons feel wilder.
  • Fire three bullets at angle - 0.2, angle and angle + 0.2 for a shotgun.

Note: The bullet starts at the muzzle, 14 pixels in front of the ship's center. Spawning at the center makes bullets appear from inside the ship, which looks wrong and, later, can make them hit the shooter.

Test yourself

Why does each bullet have a life value?

  1. To make bullets slower over time
  2. So bullets that hit nothing are removed and the array doesn't grow forever
  3. Canvas requires it
  4. To count the score

You remove bullets with splice(i, 1) inside a loop. Which loop is safe?

  1. for (let i = 0; i < a.length; i++)
  2. for (let i = a.length - 1; i >= 0; i--)
  3. for (const b of a)
  4. a.forEach((b, i) => ...)

Why is timer += DELAY better than timer = DELAY after a shot?

  1. It's shorter to type
  2. It carries the leftover time into the next gap, so the real fire rate matches the designed rate
  3. It makes the first shot faster
  4. It prevents bullets from overlapping