Shooter 3: Enemies, Spawning & Health
Now the shooter becomes a game: enemies appear at the edges of the screen and chase the player, bullets destroy them, and touching one costs health. Three systems make this work: a spawner that decides when and where enemies appear, health and damage for both sides, and invulnerability frames so one collision doesn't drain all your health at once.
Spawning from the edges
Enemies should appear just outside the screen, so they walk in instead of popping into existence next to the player. Pick a random side, then a random position along it:
function spawnPoint(rng) {
const side = Math.floor(rng() * 4); // 0 top, 1 right, 2 bottom, 3 left
const m = 16; // margin outside the screen
if (side === 0) return { x: rng() * W, y: -m };
if (side === 1) return { x: W + m, y: rng() * H };
if (side === 2) return { x: rng() * W, y: H + m };
return { x: -m, y: rng() * H };
}A spawn timer with a difficulty ramp
A spawn timer works like the fire cooldown from the last lesson: count down, spawn when it reaches zero, then add the delay. To make the game harder over time, the delay depends on how long the round has lasted. A minimum keeps it from reaching zero.
The example uses a seeded random number generator (mulberry32, a well-known tiny PRNG). Given the same seed it produces the same sequence every time, which is exactly what you want for testing, replays and "daily challenge" levels. The game below uses Math.random(), which can't be seeded.
function mulberry32(seed) {
return function () {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const W = 480, H = 270;
const spawnDelay = (t) => Math.max(0.4, 1.6 - t * 0.04); // seconds between spawns
function schedule(seed, seconds) {
const rng = mulberry32(seed);
const sides = ['top', 'right', 'bottom', 'left'];
const spawns = [];
let timer = 1; // first enemy after 1 s
for (let t = 0; t < seconds; t += 0.5) { // step in half seconds for the demo
timer -= 0.5;
while (timer <= 0) {
const side = Math.floor(rng() * 4);
const along = Math.round(rng() * (side % 2 === 0 ? W : H));
spawns.push({ t, side: sides[side], along });
timer += spawnDelay(t);
}
}
return spawns;
}
const spawns = schedule(7, 40);
for (const s of spawns.slice(0, 5)) console.log(`t=${s.t.toFixed(1)}s ${s.side.padEnd(6)} at ${s.along}`);
for (let from = 0; from < 40; from += 10) {
const n = spawns.filter((s) => s.t >= from && s.t < from + 10).length;
console.log(`${from}-${from + 10}s: ${n} enemies`);
}
console.log('same seed, same first spawn:', JSON.stringify(schedule(7, 5)[0]) === JSON.stringify(spawns[0]));t=0.5s top at 30
t=2.5s left at 189
t=4.0s bottom at 195
t=5.5s right at 65
t=6.5s bottom at 350
0-10s: 7 enemies
10-20s: 10 enemies
20-30s: 16 enemies
30-40s: 25 enemies
same seed, same first spawn: true
The count per 10 seconds climbs until the delay reaches its 0.4 s minimum at 30 seconds; from then on it stays at 25 enemies per 10 seconds. Tuning this curve is a big part of game design: too flat is boring, too steep is unfair.
Health, damage and invulnerability
Bullets damage enemies: each enemy has hp, a hit subtracts one and removes the bullet, and at zero the enemy dies and the score goes up. Bigger enemies simply start with more hp.
The player is different. Enemies keep touching the player for many frames in a row. If every frame of contact dealt damage, one bump would cost 30 health. The standard fix is invulnerability frames ("i-frames"): after a hit, the player can't be hurt again for a short time, and blinks to show it.
const DT = 1 / 60;
const IFRAMES = 1.0; // seconds of invulnerability after a hit
let hp = 5, invuln = 0;
const hits = [];
// An enemy touches the player during frames 10-40 and again during frames 100-110.
const touching = (f) => (f >= 10 && f <= 40) || (f >= 100 && f <= 110);
for (let frame = 0; frame < 120; frame++) {
invuln = Math.max(0, invuln - DT);
if (touching(frame) && invuln === 0) {
hp -= 1;
invuln = IFRAMES;
hits.push(frame);
}
}
console.log('damage taken on frames', hits.join(', '));
console.log('hp left', hp);damage taken on frames 10, 100
hp left 3
Thirty-one frames of contact cost one point of health, not thirty-one. Add a small knockback (push the player away from the enemy) and the two stop overlapping anyway.
Step 3: enemies that fight back
Survive as long as you can. Red enemies take 2 hits; the big purple ones take 6 and are slower. You have 5 hearts. Press R to restart after the game is over.
<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, IFRAMES = 1.0;
const mouse = { x: W / 2 + 80, y: H / 2, down: false };
let player, bullets, enemies, fireTimer, spawnTimer, time, score, over;
function reset() {
player = { x: W / 2, y: H / 2, r: 11, speed: 140, angle: 0, hp: 5, invuln: 0 };
bullets = []; enemies = [];
fireTimer = 0; spawnTimer = 1; time = 0; score = 0; over = false;
}
reset();
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));
const spawnDelay = (t) => Math.max(0.4, 1.6 - t * 0.04);
function spawnEnemy() {
const side = Math.floor(Math.random() * 4), m = 16;
const x = side === 1 ? W + m : side === 3 ? -m : Math.random() * W;
const y = side === 0 ? -m : side === 2 ? H + m : Math.random() * H;
const big = Math.random() < 0.15;
enemies.push(big
? { x, y, r: 15, speed: 38, hp: 6, maxHp: 6, color: '#ab47bc', points: 50 }
: { x, y, r: 9, speed: 62 + time, hp: 2, maxHp: 2, color: '#ef5350', points: 10 });
}
function fire() {
const cos = Math.cos(player.angle), sin = Math.sin(player.angle);
bullets.push({ x: player.x + cos * 14, y: player.y + sin * 14,
vx: cos * BULLET_SPEED, vy: sin * BULLET_SPEED, life: BULLET_LIFE });
}
function update(dt) {
if (over) { if (pressed.has('KeyR')) reset(); return; }
time += dt;
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);
player.invuln = Math.max(0, player.invuln - dt);
if (mouse.down || keys.has('Space')) {
fireTimer -= dt;
if (fireTimer <= 0) { fire(); fireTimer += FIRE_DELAY; }
} else fireTimer = Math.max(fireTimer - dt, 0);
spawnTimer -= dt;
while (spawnTimer <= 0) { spawnEnemy(); spawnTimer += spawnDelay(time); }
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;
if (b.life <= 0 || b.x < -10 || b.x > W + 10 || b.y < -10 || b.y > H + 10) bullets.splice(i, 1);
}
for (let i = enemies.length - 1; i >= 0; i--) {
const e = enemies[i];
const ex = player.x - e.x, ey = player.y - e.y, d = Math.hypot(ex, ey) || 1;
e.x += (ex / d) * e.speed * dt; // chase the player
e.y += (ey / d) * e.speed * dt;
for (let j = bullets.length - 1; j >= 0; j--) { // bullet vs enemy (circle vs point)
const b = bullets[j];
if (Math.hypot(b.x - e.x, b.y - e.y) < e.r + 2) {
bullets.splice(j, 1);
e.hp -= 1;
e.flash = 0.06;
break;
}
}
e.flash = Math.max(0, (e.flash || 0) - dt);
if (e.hp <= 0) { score += e.points; enemies.splice(i, 1); continue; }
if (d < e.r + player.r && player.invuln === 0) { // enemy vs player (circle vs circle)
player.hp -= 1;
player.invuln = IFRAMES;
player.x = clamp(player.x + (ex / d) * 24, player.r, W - player.r); // knockback
player.y = clamp(player.y + (ey / d) * 24, player.r, H - player.r);
if (player.hp <= 0) over = true;
}
}
}
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(); }
for (const e of enemies) {
const x = Math.round(e.x), y = Math.round(e.y);
ctx.fillStyle = e.flash > 0 ? '#fff' : e.color;
ctx.beginPath(); ctx.arc(x, y, e.r, 0, Math.PI * 2); ctx.fill();
if (e.maxHp > 2) { // health bar for big enemies
ctx.fillStyle = '#333'; ctx.fillRect(x - 12, y - e.r - 7, 24, 3);
ctx.fillStyle = '#66bb6a'; ctx.fillRect(x - 12, y - e.r - 7, Math.round(24 * e.hp / e.maxHp), 3);
}
}
ctx.fillStyle = '#ffee58';
for (const b of bullets) ctx.fillRect(Math.round(b.x) - 2, Math.round(b.y) - 2, 4, 4);
const blink = player.invuln > 0 && Math.floor(player.invuln * 12) % 2 === 0;
if (!blink) drawShip(player.x, player.y, player.angle);
ctx.fillStyle = '#ff5252'; ctx.font = '14px system-ui, sans-serif'; ctx.textAlign = 'left';
ctx.fillText('♥'.repeat(Math.max(0, player.hp)), 8, 18);
ctx.fillStyle = '#e0e0e0'; ctx.textAlign = 'right';
ctx.fillText(`score ${score} ${time.toFixed(0)}s`, W - 8, 18);
if (over) banner('Game over', `score ${score} - press R to play again`);
}
run(update, draw, 'WASD to move, mouse to aim, hold Space or click to fire');
</script>How the new pieces fit together:
reset()puts every piece of state back to its starting value. Writing it as one function from the start makes "play again" trivial and avoids bugs where one variable keeps its old value.- Chasing is the same normalized vector as player movement, but pointing from the enemy to the player.
- Bullet vs enemy is a point-in-circle test; enemy vs player is circle vs circle (see Collision Detection). The bullet loop
breaks after a hit so one bullet can't damage two enemies. - Hit flash:
e.flashmakes an enemy white for 60 ms when hit. It costs three lines and makes shooting feel far better. overfreezes the update. The game still draws, with a banner on top.
Tip: Every loop here is "each bullet × each enemy". With 50 bullets and 40 enemies that's 2,000 distance checks per update, still nothing for a modern CPU. Past a few hundred objects, a spatial grid (only test objects in nearby cells) is the next step.
Test yourself
Why do enemies spawn a few pixels outside the screen?
- The canvas can't draw near the edge
- So they walk into view instead of appearing suddenly, possibly on top of the player
- It makes collision faster
- Spawning inside is not allowed by the browser
What problem do invulnerability frames solve?
- Enemies moving too fast
- One continuous contact dealing damage every frame and draining all health at once
- Bullets passing through enemies
- The game running at different frame rates
What is the main benefit of a seeded random number generator like mulberry32?
- It's more random than
Math.random() - The same seed always produces the same sequence, so results are reproducible
- It's required for canvas games
- It never repeats a number