TExcelTAD

Particles

A particle is a tiny, short-lived object: a spark, a speck of dust, a drop of water, a puff of smoke. One particle is boring, but a few hundred of them, each with its own speed and lifetime, turn a plain collision into an explosion. Particles are the cheapest "juice" you can add to a game: they don't change the rules at all, yet the game instantly feels more alive.

Anatomy of a particle

Every particle system is built from the same few fields:

Field Meaning
x, y Position in pixels
vx, vy Velocity in pixels per second
life, max Age so far and total lifetime in seconds
size, color How it looks; often both change with age
alive Whether this slot is in use (for pooling)

Each update you move every live particle, add gravity or drag, increase its age and kill it when life >= max. When you draw, use the age ratio life / max (0 at birth, 1 at death) to fade it out, shrink it or shift its colour.

The code that creates particles is called an emitter. A burst emitter creates many at once (an explosion). A continuous emitter creates a few every frame (a trail, a fire, a fountain).

A pooled particle system

An explosion can create 100 objects in one frame and throw them away half a second later. Creating and discarding that many objects keeps the garbage collector busy, which can cause small stutters. The usual fix is a pool: allocate a fixed array of particles once, and reuse dead slots instead of creating new objects. When the pool is full, new particles are simply dropped: nobody notices one spark fewer.

This pure-logic version uses a seeded random generator, so the output is the same on every run:

js · try it yourself
// mulberry32: a tiny seeded random generator (same seed -> same numbers)
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 rand = mulberry32(7);

class ParticlePool {
  constructor(size) {
    this.items = Array.from({ length: size }, () => ({ alive: false, x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 0 }));
    this.dropped = 0;
  }
  emit(x, y, max) {
    const p = this.items.find((q) => !q.alive);   // reuse a dead slot
    if (!p) { this.dropped++; return; }             // pool full: drop it
    const angle = rand() * Math.PI * 2;
    Object.assign(p, { alive: true, x, y, vx: Math.cos(angle) * 50, vy: Math.sin(angle) * 50, life: 0, max });
  }
  update(dt) {
    for (const p of this.items) {
      if (!p.alive) continue;
      p.vy += 200 * dt;            // gravity
      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.life += dt;
      if (p.life >= p.max) p.alive = false;
    }
  }
  get alive() { return this.items.filter((p) => p.alive).length; }
}

const pool = new ParticlePool(8);
for (let i = 0; i < 5; i++) pool.emit(100, 100, 0.5);
console.log('after burst 1:', pool.alive, 'alive');
for (let i = 0; i < 5; i++) pool.emit(100, 100, 1.0);
console.log('after burst 2:', pool.alive, 'alive,', pool.dropped, 'dropped');

for (let step = 1; step <= 4; step++) {
  pool.update(0.25);
  console.log(`t=${(step * 0.25).toFixed(2)}s alive=${pool.alive}`);
}
const alpha = (life, max) => (1 - life / max).toFixed(2);
console.log('alpha at age 0, 0.25, 0.5 of 1s:', alpha(0, 1), alpha(0.25, 1), alpha(0.5, 1));
after burst 1: 5 alive
after burst 2: 8 alive, 2 dropped
t=0.25s alive=8
t=0.50s alive=3
t=0.75s alive=3
t=1.00s alive=0
alpha at age 0, 0.25, 0.5 of 1s: 1.00 0.75 0.50

The first burst's particles live 0.5 s, so after two quarter-second steps only the three long-lived ones remain. Two particles of the second burst never existed because the pool was full.

Sparks and trails, playable

Move the orange square with the arrow keys: it leaves a trail (a continuous emitter). Press Space for an explosion (a burst emitter). The counter shows how many of the 400 pool slots are in use.

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 MAX = 400;
const pool = Array.from({ length: MAX }, () => ({ alive: false, x: 0, y: 0, vx: 0, vy: 0, life: 0, max: 1, size: 3, hue: 0 }));
const player = { x: 240, y: 135, speed: 170 };

function emit(x, y, speed, life, size, hue) {
  for (const p of pool) {
    if (p.alive) continue;
    const a = Math.random() * Math.PI * 2;
    const s = speed * (0.3 + Math.random() * 0.7);
    p.alive = true; p.x = x; p.y = y;
    p.vx = Math.cos(a) * s; p.vy = Math.sin(a) * s;
    p.life = 0; p.max = life * (0.5 + Math.random() * 0.5);
    p.size = size; p.hue = hue + Math.random() * 40;
    return true;
  }
  return false;               // pool is full
}
function burst(x, y, n) {
  for (let i = 0; i < n; i++) if (!emit(x, y, 220, 0.9, 4, 10)) break;
}

function update(dt) {
  let dx = 0, dy = 0;
  if (keys.has('ArrowLeft')) dx -= 1;
  if (keys.has('ArrowRight')) dx += 1;
  if (keys.has('ArrowUp')) dy -= 1;
  if (keys.has('ArrowDown')) dy += 1;
  player.x = Math.max(8, Math.min(W - 8, player.x + dx * player.speed * dt));
  player.y = Math.max(8, Math.min(H - 8, player.y + dy * player.speed * dt));
  if (dx || dy) for (let i = 0; i < 2; i++) emit(player.x, player.y, 30, 0.5, 3, 180);
  if (pressed.has('Space')) burst(player.x, player.y, 90);

  for (const p of pool) {
    if (!p.alive) continue;
    p.vy += 160 * dt;                 // gravity
    p.vx *= 1 - 1.5 * dt;             // air drag
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.life += dt;
    if (p.life >= p.max) p.alive = false;
  }
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  let n = 0;
  for (const p of pool) {
    if (!p.alive) continue;
    n++;
    const k = p.life / p.max;                       // 0 = newborn, 1 = dead
    ctx.globalAlpha = 1 - k;                        // fade out
    ctx.fillStyle = `hsl(${p.hue} 100% ${70 - k * 30}%)`;
    const s = Math.max(1, Math.round(p.size * (1 - k * 0.6)));   // shrink
    ctx.fillRect(Math.round(p.x - s / 2), Math.round(p.y - s / 2), s, s);
  }
  ctx.globalAlpha = 1;
  ctx.fillStyle = '#ffb74d';
  ctx.fillRect(Math.round(player.x - 8), Math.round(player.y - 8), 16, 16);
  ctx.fillStyle = '#fff';
  ctx.font = '12px monospace';
  ctx.textAlign = 'left';
  ctx.fillText(`particles ${n}/${MAX}`, 8, 16);
}

run(update, draw, 'Arrows move, Space explodes');
</script>

Fire and additive blending

Fire, magic and lasers glow because overlapping particles add up their light. Canvas can do that with ctx.globalCompositeOperation = 'lighter': where particles overlap, the colours are added together and turn bright yellow-white. Press B to switch between normal and additive blending, and Up/Down to change how many particles the emitter creates per second.

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 pool = Array.from({ length: 600 }, () => ({ alive: false }));
let rate = 180, carry = 0, additive = true;

function spawn() {
  const p = pool.find((q) => !q.alive);
  if (!p) return;
  p.alive = true;
  p.x = W / 2 + (Math.random() - 0.5) * 30;
  p.y = H - 30;
  p.vx = (Math.random() - 0.5) * 40;
  p.vy = -60 - Math.random() * 80;
  p.life = 0;
  p.max = 0.6 + Math.random() * 0.6;
}

function update(dt) {
  if (pressed.has('KeyB')) additive = !additive;
  if (keys.has('ArrowUp')) rate = Math.min(600, rate + 200 * dt);
  if (keys.has('ArrowDown')) rate = Math.max(10, rate - 200 * dt);
  carry += rate * dt;                 // fractional particles carry over to the next step
  while (carry >= 1) { spawn(); carry--; }
  for (const p of pool) {
    if (!p.alive) continue;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.vx += (W / 2 - p.x) * 1.5 * dt;  // pull towards the centre: a flame shape
    p.life += dt;
    if (p.life >= p.max) p.alive = false;
  }
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  ctx.globalCompositeOperation = additive ? 'lighter' : 'source-over';
  for (const p of pool) {
    if (!p.alive) continue;
    const k = p.life / p.max;
    ctx.fillStyle = `hsla(${40 - k * 40}, 100%, ${55 - k * 25}%, ${0.5 * (1 - k)})`;
    const r = 10 * (1 - k) + 2;
    ctx.beginPath();
    ctx.arc(p.x, p.y, r, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.globalCompositeOperation = 'source-over';
  ctx.fillStyle = '#fff';
  ctx.font = '12px monospace';
  ctx.textAlign = 'left';
  ctx.fillText(`${additive ? 'additive' : 'normal'} blending, ${Math.round(rate)} particles/s`, 8, 16);
}

run(update, draw, 'B toggles blending, Up/Down change the rate');
</script>

Notice the carry variable: at 180 particles per second and 60 updates per second the emitter must create exactly 3 per step, but at 100 per second it needs 1.67. Keeping the fraction for the next step makes the rate exact at any frame rate.

Tips for good-looking particles

Idea How
Vary everything a little Random speed, lifetime, size and hue in a range, never one fixed value
Fade and shrink Alpha 1 - k plus a smaller size near the end looks smoother than either alone
Inherit velocity Particles from a moving object start with part of its velocity
Cap the count A fixed pool means a huge explosion can never freeze the game
Draw rectangles for small sparks fillRect is much cheaper than arc + fill

Tip: Particles are decoration, so they don't need the fixed-step accuracy of gameplay code. Some games update them in the render pass with the real frame time; keeping them in update (as here) is simpler and still cheap.

Note: Pooling is covered in more depth in Shooter 4: Object Pooling, where we measure what it actually saves.

Test yourself

What does a particle pool do when every slot is already in use?

  1. Doubles the array size
  2. Throws an error
  3. Drops the new particle
  4. Kills the oldest particle and crashes

Which canvas setting makes overlapping particles add their colours together (a glow)?

  1. ctx.globalAlpha = 2
  2. ctx.globalCompositeOperation = 'lighter'
  3. ctx.filter = 'blur(2px)'
  4. ctx.imageSmoothingEnabled = true

An emitter should create 100 particles per second at 60 updates per second. Why keep a fractional carry?

  1. To make particles bigger
  2. So the rate stays exact even though 100/60 is not a whole number
  3. Because Math.random needs it
  4. To save memory