Lesson 9 of 10

A particle system

Goal

Create, move and safely remove particles

01

Explanation

Sparks, smoke and explosions aren't ready-made drawings. They're hundreds of tiny dots, each with a position, a velocity and a lifetime in seconds. On every frame a particle moves by its velocity and its lifetime drops by dt, and once its lifetime runs out, it's removed.

Removing items while you loop over an array is a well-known bug. splice(i, 1) shifts every element after i back one slot, so a loop that starts at the front of the array skips the next particle and doesn't update it that frame. The fix is to loop over the array from the end, because then the shift only touches elements you've already visited.

You also need a cap. Every explosion adds dozens of particles, and explosions in quick succession weigh down every frame until the game stutters, so no new particle is created once you reach max. And take every random value from the rng passed to the function, so the same explosion repeats exactly in a test.

02

Your task

Write emit(system, x, y, count, rng) to add up to count particles to system.particles, all starting at the point (x, y), without going over system.max. Each particle is shaped like { x, y, vx, vy, life } and gets its speed, direction and lifetime from rng. Then write update(system, dt) to move each particle by vx * dt and vy * dt, reduce its life by dt, and remove every particle whose lifetime has reached zero or less.

Checks

6 checks
  1. emit adds count particles at the point
  2. emit never goes over max
  3. A particle moves by its velocity × dt
  4. The lifetime drops by dt
  5. An expired particle is removed without skipping the next one
  6. Every random value comes from rng
03

Hints

0/3
index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.