Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Particle Systems in Three.js

Stars, snow, sparks, rain, magic dust: every game is full of tiny things that move together. In this part you draw thousands of them as one object, look inside a geometry for the first time, and switch between a starfield, a snowstorm, and a fountain by changing a few lines of rules.

Part 12 of 12 ~15 min JavaScript
Part 12 of 12

What you'll learn

  • What a particle system is, and why three.js draws ten thousand dots as one THREE.Points object instead of ten thousand meshes.
  • How a geometry stores its points: one flat Float32Array where particle number i keeps its x, y, and z at indexes i*3, i*3+1, and i*3+2.
  • How to move every particle each frame with delta time, wrap the ones that leave the box, and tell three.js the data changed with needsUpdate = true.
  • How PointsMaterial options (size, size attenuation, additive blending, a soft canvas dot) turn squares into snow and sparks, and how three tiny rule sets become a starfield, snow, and a fountain.

The Big Idea

Thousands of dots, one simple rule, one object

Look closely at snow in any game. No single flake is interesting. It is a dot. It falls, drifts a little, and when it reaches the ground another dot appears at the top. But a thousand of them doing that at slightly different speeds looks like weather. The same is true of sparks from a sword hit, stars rushing past a spaceship, dust in a sunbeam, and the spray of a fountain. Each piece is trivial; the crowd is the effect. That is a particle system: many tiny things, each following the same small rule, and your eye does the rest.

Your first instinct might be to build snow the way you built everything else: a for loop that makes a thousand tiny Mesh objects. It would work, and it would be slow. Every mesh is a separate order to the graphics card, a separate draw call: "here is a shape, here is its material, draw it." Ten thousand orders a frame is like sending a delivery truck ten thousand times with one package each. The trips add up, and your frame rate falls apart long before the card is actually busy.

Three.js has a better vehicle. THREE.Points takes a geometry with one vertex per particle (a vertex is just a point in space) and a PointsMaterial that says how to draw a dot at each vertex, and draws all of them in one draw call. One truck, ten thousand packages. The graphics card is built for exactly this job, so even 100,000 points costs it almost nothing. The only work left for your JavaScript is deciding where each dot goes this frame.

To do that you finally have to look inside a geometry. So far a geometry has been a black box: ask for a BoxGeometry, get a cube. Under the hood every geometry is a list of numbers, and on this page you write that list yourself. Once you can read and change it, you can move a snowflake, and in Part 14 the same skill builds whole landscapes.

Simple definitions: a particle is one tiny dot with a position and a rule for how it moves. A particle system is thousands of them drawn together as one THREE.Points object. The position attribute is the flat array of numbers inside the geometry that says where every particle is. A draw call is one order to the graphics card; fewer is faster.


How It Works

The array, the loop, the material

The setup from Part 1 and the delta-time loop from Part 7 stay exactly as they were. Everything new is in four pieces: a flat array of positions, a Points object that draws it, a loop that changes the numbers and says so, and a material that makes the dots look like something.

1. The flat array: three slots per particle

Imagine a very long shelf. Every particle owns three slots in a row: one for x, one for y, one for z. Particle 0 gets slots 0, 1, and 2. Particle 1 gets 3, 4, and 5. Particle 2 gets 6, 7, and 8. In general, particle number i keeps its x at slot i * 3, its y at i * 3 + 1, and its z at i * 3 + 2. There is no list of little {x, y, z} objects, just one array of plain numbers, because that is what the graphics card wants: one flat block of memory it can copy in a single move.

The array is a Float32Array: a JavaScript array that holds only decimal numbers and never changes length. new Float32Array(count * 3) makes one with room for every particle, filled with zeros, and a for loop gives each particle a random spot. THREE.MathUtils.randFloatSpread(14) returns a random number between -7 and 7: a spread of 14 centered on zero.

Then you hand the array to a BufferGeometry, the raw, empty geometry every other geometry is built from. geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)) says: "this array is the position attribute, and every 3 numbers make one vertex." Finally, new THREE.Points(geometry, material) is the object you add to the scene, the same way you added a Mesh. A mesh connects its vertices into triangles; Points draws a dot at each one and stops there.

particles.js
// One flat array: x, y, z, x, y, z, ... three slots per particle.
const count = 8000;
const positions = new Float32Array(count * 3);      // 24,000 numbers, all 0 for now

for (let i = 0; i < count; i++) {
  positions[i * 3]     = THREE.MathUtils.randFloatSpread(14);   // x: somewhere in -7..7
  positions[i * 3 + 1] = THREE.MathUtils.randFloatSpread(10);   // y: -5..5
  positions[i * 3 + 2] = THREE.MathUtils.randFloatSpread(10);   // z: -5..5
}

// A raw geometry, told that these numbers are its vertex positions, 3 per vertex.
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));

// How to draw a dot at each vertex.
const material = new THREE.PointsMaterial({
  color: 0xe879f9,
  size: 0.12,                      // in world units, like everything else
  sizeAttenuation: true,           // far dots draw smaller
  map: dotTexture,                 // a soft round dot (see dot.js below)
  transparent: true,
  opacity: 0.9,
  depthWrite: false,               // dots never block each other
  blending: THREE.AdditiveBlending,   // overlapping dots add up and glow
});

const points = new THREE.Points(geometry, material);   // ONE object, one draw call
points.frustumCulled = false;                          // always draw it (see Common mistakes)
scene.add(points);

This is what the Try It stage builds in Snow mode. The Count slider changes the 8000, and the material lines map one-to-one onto the toggles. new THREE.Float32BufferAttribute(positions, 3) is a shortcut that does the same job as BufferAttribute here.

2. The loop: change the numbers, then say so

Now the particles need to move. Every frame, loop over the array and change the numbers. For snow, that means pulling y down: positions[i * 3 + 1] -= speeds[i] * dt. The dt is the delta time from Part 7, so a speed is in units per second and the snow falls at the same rate on a fast laptop and a slow phone. When a flake drops below the floor of the box, do not delete it; a Float32Array cannot change length anyway. Instead wrap it: put it back at the top at a fresh random x. To the viewer, an old flake landing and a new one appearing are the same event.

Where does speeds come from? If every flake fell at the same speed, the whole sheet of snow would slide down like wallpaper. So each particle gets its own speed in a second, smaller array, speeds[i], picked randomly between 0.6 and 1.8 when the system is built. This is a plain array your JavaScript reads; three.js never sees it. Per-particle variety like this is most of what makes an effect feel natural. The sway is one term: Math.sin(time + i) * sway * dt nudges x left and right, and adding i inside the sine puts every flake at a different point in its wobble.

Then the line this whole page is about. Changing positions changes your copy, in JavaScript memory. The graphics card has its own copy, uploaded when the geometry was first drawn, and it has no idea you touched anything. geometry.attributes.position.needsUpdate = true is you raising your hand: "the data changed, please copy it over again before the next draw." It is the texture.needsUpdate idea from Part 8, applied to positions instead of pixels. Forget it and the loop runs perfectly, the array changes perfectly, and nothing on screen moves.

snow.js
// Per-particle variety: every flake gets its own fall speed, in units per second.
const speeds = new Float32Array(count);
for (let i = 0; i < count; i++) speeds[i] = 0.6 + Math.random() * 1.2;   // 0.6 .. 1.8

let sway = 1;        // how hard the wind pushes sideways
let time = 0;

function updateSnow(dt) {
  time += dt;
  for (let i = 0; i < count; i++) {
    positions[i * 3 + 1] -= speeds[i] * dt;                      // fall: y goes down
    positions[i * 3]     += Math.sin(time + i) * sway * dt;      // drift: x wobbles, each flake out of step

    if (positions[i * 3 + 1] < -5) {                            // below the floor of the box?
      positions[i * 3 + 1] = 5;                                 // wrap: back to the top
      positions[i * 3]     = THREE.MathUtils.randFloatSpread(14);   // at a new x
    }
  }
  geometry.attributes.position.needsUpdate = true;   // "the numbers changed, re-upload them"
}

function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);   // the delta-time loop from Part 7
  updateSnow(dt);
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

The loop only ever reads and writes numbers: no objects are created, nothing joins or leaves the scene, and the array stays exactly count * 3 long. That is why it stays fast. In the demo, the Speed slider multiplies dt before the rules run, like a slow-motion or fast-forward dial, and the Sway slider is sway.

3. Three rule sets, one system

Here is the part that makes particles fun: the array, the Points, and the material never change. Only the rule inside the loop does, and the rule is a few lines. Swap it and snow becomes a starfield; swap it again and it becomes a fountain.

starfield

fly toward the camera, wrap to the back

Stars fill a long box that stretches away from the camera. Each frame z += speeds[i] * 4 * dt. A star that passes the camera jumps back to the far end. Fast enough and it feels like warp speed.

snow

fall, sway, wrap to the top

y -= speeds[i] * dt, plus a sine wobble in x. Below the floor, back to the ceiling at a new x. The per-flake speed is what keeps it from looking like a sliding sheet.

fountain

launch up, gravity pulls down, respawn

Every particle has a velocity. Each frame gravity shrinks the upward velocity, the velocity moves the position, and a particle that falls below the floor is relaunched from the nozzle.

The fountain deserves a closer look, because it is your first taste of the physics in Part 18. Snow and stars move at a fixed speed forever. A fountain droplet leaves the nozzle fast and upward, slows, hangs for an instant at the top of its arc, and comes back down faster and faster. To model that you need a second flat array, velocities, laid out exactly like positions but holding how fast each particle is moving in x, y, and z, in units per second. Then there are just two rules. Gravity changes the velocity: velocities[i * 3 + 1] -= g * dt. The velocity changes the position: positions[i * 3 + 1] += velocities[i * 3 + 1] * dt. That is all a physics engine does, thousands of times a frame. When a droplet falls below the floor, launch(i) sends it back to the nozzle with a fresh upward velocity and a small random sideways push, which fans the spray out.

fountain.js
// A second flat array, same layout: how fast each particle moves in x, y, z (units per second).
const velocities = new Float32Array(count * 3);
let g = 9.8;                                        // gravity: how much upward speed is lost per second

function launch(i) {
  positions[i * 3] = 0;  positions[i * 3 + 1] = -3;  positions[i * 3 + 2] = 0;   // the nozzle
  velocities[i * 3]     = THREE.MathUtils.randFloatSpread(1.6);   // a little sideways
  velocities[i * 3 + 1] = 6 + Math.random() * 3;                  // mostly up: 6 .. 9 per second
  velocities[i * 3 + 2] = THREE.MathUtils.randFloatSpread(1.6);
}

// Start everyone partway through a flight, so the fountain is full from frame one.
for (let i = 0; i < count; i++) {
  launch(i);
  const age = Math.random() * 1.5;                          // seconds already in the air
  positions[i * 3]     += velocities[i * 3] * age;
  positions[i * 3 + 1] += velocities[i * 3 + 1] * age - 0.5 * g * age * age;
  positions[i * 3 + 2] += velocities[i * 3 + 2] * age;
  velocities[i * 3 + 1] -= g * age;
}

function updateFountain(dt) {
  for (let i = 0; i < count; i++) {
    velocities[i * 3 + 1] -= g * dt;                    // gravity pulls the velocity down
    positions[i * 3]     += velocities[i * 3] * dt;      // velocity moves the position
    positions[i * 3 + 1] += velocities[i * 3 + 1] * dt;
    positions[i * 3 + 2] += velocities[i * 3 + 2] * dt;
    if (positions[i * 3 + 1] < -3.5 || positions[i * 3 + 1] > 12) launch(i);   // below the floor (or, with no gravity, off the top)
  }
  geometry.attributes.position.needsUpdate = true;
}

The Gravity slider is g. The warm-up loop uses the school formula for height under gravity, v * t - 0.5 * g * t * t, to fast-forward each droplet into its flight; without it every droplet would leave the nozzle in one clump on the first frame.

4. Making dots look like something

By default a point is a square: fine for a distant star, terrible for a snowflake. Three material settings fix that, and the demo has a toggle for each. First, size is in world units, so a 0.12 dot is about a tenth of your Part 1 cube. With sizeAttenuation: true, far dots draw smaller and near dots larger, like real objects, and that alone is what sells a starfield: the stars that seem to rush at you are the ones getting bigger. Turn it off and every dot is the same pixel size at any distance, which suits a HUD marker but never snow.

Second, the dot needs to be round and soft. You already know how to make a texture from a 2D canvas (Part 8): draw a white circle that fades to transparent at its edge with a radial gradient, wrap it in a CanvasTexture, and set it as the material's map. Because the texture is white, the material's color tints it, so one texture serves pink stars and white snow alike. The fade needs transparent: true, and you want depthWrite: false, which tells the dots not to record their distance in the depth buffer. Without it, a near dot's invisible square corners still block the dots behind it, and every particle gets a dark box where it overlaps another.

Third, blending. Normal blending paints each dot over what is behind it, like paint. THREE.AdditiveBlending adds the dot's color to what is behind it, like light: where many dots overlap the color piles up toward white and the cluster glows. That is the look of sparks, magic, and neon stars. For snow, which is not a light source, normal blending is more honest.

dot.js
// A soft white dot drawn on a 2D canvas, so no image files are needed. The material's color tints it.
function makeDotTexture() {
  const c = document.createElement('canvas');
  c.width = c.height = 64;
  const ctx = c.getContext('2d');
  const grad = ctx.createRadialGradient(32, 32, 0, 32, 32, 32);   // center → edge
  grad.addColorStop(0,   'rgba(255, 255, 255, 1)');     // solid in the middle
  grad.addColorStop(0.4, 'rgba(255, 255, 255, 0.6)');
  grad.addColorStop(1,   'rgba(255, 255, 255, 0)');     // invisible at the edge
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, 64, 64);
  return new THREE.CanvasTexture(c);
}
const dotTexture = makeDotTexture();

// Optional: a color per particle. Add a 'color' attribute (r, g, b per vertex) and turn on vertexColors.
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
material.vertexColors = true;

Per-particle color is a second attribute, laid out like position but holding red, green, blue from 0 to 1; with vertexColors: true the material multiplies its own color by each vertex's. The hero starfield uses it to tint each star somewhere between fuchsia and white. A few settings (map, sizeAttenuation, vertexColors) change how the material's shader is built, so after flipping one at runtime set material.needsUpdate = true; the demo does.

A note on speed. The update loop is plain JavaScript that touches every particle every frame: with 20,000 particles that is 60,000 numbers, sixty times a second. Modern devices handle that comfortably, and the draw is one call no matter the count, so the demo's frame rate barely moves between 1,000 and 20,000. Push to hundreds of thousands and the JavaScript loop, not the drawing, becomes the bottleneck. Serious effects then move the math onto the graphics card in a small program called a shader. That is a later adventure; everything on this page is the version you can read and change.


Try It

Stars, snow, fountain

One Points object, one flat array, three rule sets. The Mode buttons swap the rule and re-scatter the same array; the Count slider builds a new array and disposes the old one; everything else is a line of PointsMaterial. The chip counts particles, draw calls, and frames per second, and the live code below the controls shows the lines you are editing.

the rule

Mode same array, same Points, different lines inside the loop
8,000
×1.0
9.8
1.0

PointsMaterial

0.12
#e879f9
Look map, blending, and sizeAttenuation
Live code: the lines these controls edit
const positions = new Float32Array(8000 * 3);              // 24,000 numbers on the shelf
positions[i * 3 + 1] -= speeds[i] * dt;                 // snow: fall, then sway, then wrap to the top
geometry.attributes.position.needsUpdate = true;          // dt this frame = clock delta × 1.0
material.size = 0.12;   material.sizeAttenuation = true;   material.map = dotTexture;
material.blending = THREE.AdditiveBlending;   material.color.set('#e879f9');
  1. Drag Count all the way to 20,000 and watch the fps in the chip. It barely moves, even though the JavaScript loop now touches 60,000 numbers a frame. The alternative, 20,000 separate meshes, would be 20,000 draw calls; the chip's "1 draw call" is the whole reason this page works. Slide Count back down and notice the particles re-scatter: a new Float32Array was built and the old geometry disposed.
  2. Stay on Snow and turn off Soft dots, then Additive glow. With the round texture gone every flake is a hard square, and with normal blending overlapping squares paint over each other instead of adding up. Turn both back on and the softness and glow return. Now switch to Starfield and turn off Size attenuation: the stars stop growing as they approach, and the feeling of depth disappears even though not one position changed.
  3. Pick Fountain, push Gravity to 30, then drag it to 0. At 30 the droplets barely clear the nozzle before they are yanked back down: a fizzing puddle. At 0 nothing slows them, so they rise in straight lines and only respawn when they pass the ceiling at y > 12. Set it near 9.8 again and the spray arcs like water. You just changed a physics simulation with one number, which is Part 18 in miniature.

Watch Out

Common mistakes

Particle bugs are silent: no error in the console, just dots that do the wrong thing or nothing at all. These four cover almost every first attempt.

Nothing moves

Your loop changes every number in positions, logging proves the values are changing, yet the particles sit perfectly still. The graphics card is still drawing the copy it got on the first frame.

Fix: after the loop, geometry.attributes.position.needsUpdate = true. Without it the new numbers are never uploaded. Same idea as texture.needsUpdate in Part 8.

A new geometry every frame

To "update" the particles you build a fresh Float32Array, a fresh BufferGeometry, and a fresh Points each frame. It moves, but it stutters, and memory climbs until the tab crawls.

Fix: build the array and geometry once, change the numbers in place, and flag needsUpdate. Rebuild only when the count changes, and call geometry.dispose() on the one you replace, like the Count slider does.

Blocky dots with dark corners

Every particle is a hard square, and where two overlap the front one has a dark box around it that punches a hole in the one behind. Snow looks like confetti.

Fix: give the material a soft round map (the CanvasTexture dot), set transparent: true, and set depthWrite: false so the invisible corners cannot block anything. If you keep depth writing on for some reason, alphaTest: 0.5 discards the see-through pixels instead.

Particles vanish when the camera moves

The snow looks fine, then you swing the camera or move the particles far from where they started and the whole system blinks out. Three.js skips objects whose bounding sphere is off screen, and that sphere was computed from the starting positions and never updated.

Fix: for an effect that fills the view, points.frustumCulled = false is the simplest answer: always draw it, no sphere to keep current. If the system is small and you want culling, call geometry.computeBoundingSphere() after any big change of positions.


Your Turn

Check your understanding

Snowflake number 250 is stored in a flat position array. Which three indexes hold its x, y, and z, and what one line do you add after moving it so the change shows up on screen?

Your answer:

Sample answer: particle i lives at i * 3, i * 3 + 1, and i * 3 + 2, so flake 250's x, y, and z are at indexes 750, 751, and 752. After changing them, add geometry.attributes.position.needsUpdate = true so three.js re-uploads the array before the next frame. That line goes once per frame, after the whole loop, not once per flake.


Check Yourself

Quick quiz

1. Why is one THREE.Points object with 10,000 vertices so much faster than 10,000 small meshes?

2. What does geometry.attributes.position.needsUpdate = true actually tell three.js?

3. A friend turns sizeAttenuation off on a starfield and says it "looks flat." What changed?

Keep learning

You can now fill a scene with thousands of moving things for the price of one object: a flat Float32Array with three slots per particle, a Points to draw it, a rule that changes the numbers each frame using dt, and needsUpdate to make the change visible. More parts are on the way: scores and HUDs, collision, game state, and a complete game.

Part of the Games and Animations with Three.js tutorial series.