Making a falling sand simulator
This post is part of a series. Be sure to check the bottom of the article for the next post!
What this post explains
This post walks through building a falling sand simulation in JavaScript with p5.js. It starts with a 2D grid of particles, adds gravity, and then adds simple local movement rules so sand can fall, settle, and slide in the browser.
Over the years there have been a number of projects focusing on building systems of particle materials that interact with one another. The first I saw was called "Powder Game", which had all kinds of features and was written in Java. More recently there has been Sandspiel and an entire roguelike game (ignoring the Berlin Interpretation for a moment) built on the idea that the entire environment is made of particle materials similar to falling sand games, called Noita (which is pretty fantastic and you should give it a try!).
A fun exercise is implementing one of these falling material particle systems.
A falling sand simulation is a grid-based particle system: each cell stores a material, and each frame applies small local rules that create sand-like behavior.
In this post, we'll implement the most basic material, sand, and focus on the core simulation loop that makes a browser-based falling sand demo work.
This will be the final product for this post (drag around inside!):
Let's get started!
Drawing particles to the screen
So first things first, we need a way to draw some pixels on the screen and keep track of their positions. Here we're using p5.js with a bit of abstraction to simplify things. If you want to implement this yourself, feel free to check the source code for all the details I'm skipping over. I'm hoping I gave enough here that you could pick up another engine and implement this without issue.
We can build a Grid class to represent our pixels with the functions we need to interact with it.
This grid is the simulation state: every index represents one cell in the falling sand world.
class Grid {
initialize(width, height) {
this.width = width;
this.height = height;
this.grid = new Array(width * height).fill(0);
}
// Allow us to clear the canvas
clear() {
this.grid = new Array(this.width * this.height).fill(0);
}
// Allow us to set a specific particle
set(x, y, color) {
this.grid[y * this.width + x] = color;
}
// Allow us to swap two particles (or space)
swap(a, b) {
const temp = this.grid[a];
this.grid[a] = this.grid[b];
this.grid[b] = temp;
}
// Check if a particle exists in a space
isEmpty(index) {
return this.grid[index] === 0;
}
}
Now we need a way to actually place particles on the screen. We'll assume there's a left-click method available, and use this to set that particle in our grid.
p.onLeftClick = (x, y) => {
// Vary the color slightly for aesthetics
let color = varyColor(p, SAND_COLOR);
grid.set(x, y, color);
};
We also added some variation to the color to make it feel a bit higher quality. All we're doing is adding some randomness to the saturation and lightness.
function varyColor(p, color) {
let hue = p.floor(p.hue(color));
let saturation = p.saturation(color) + p.floor(p.random(-20, 0));
saturation = p.constrain(saturation, 0, 100);
let lightness = p.lightness(color) + p.floor(p.random(-10, 10));
lightness = p.constrain(lightness, 0, 100);
return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}
And now we can just iterate through the grid and set the corresponding pixels each loop of our draw call.
At this point rendering and simulation are still separate ideas: the grid stores particle state, and the draw loop turns that state into visible pixels.
// This happens every frame
this.grid.forEach((color, index) => {
setPixel(p, index, color || background);
})
Nice, now we can click, drag, and draw some particles. It's not great, but it's something!
Awesome! Let's add gravity.
Adding gravity with a local particle rule
Before we implement our first rule, it's worth stating explicitly that all rules will be applied once per frame. This gives all particles equal opportunity to fulfill their rule, before another particle gets to apply their rule a second time.
Our first rule: gravity.
Sand-like behavior comes from local movement rules, not from simulating real physics directly.
The rule is as follows: if the space below a particle is empty, swap it with the empty space.
updatePixel(i) {
const below = i + this.width;
// If there are no pixels below, move it down.
if (this.isEmpty(below)) {
this.swap(i, below)
}
}
update() {
// Go through each pixel one by one and apply the rule
for (let i = 0; i < this.grid.length - this.width - 1; i++) {
this.updatePixel(i);
}
}
Try drawing a bit on the canvas!
Hm... Something isn't working quite right! We don't actually see the particles falling! They just instantly appear.
Let's take a crack at fixing that!
Fixing gravity by changing update order
What's going on here?
Well, if we take another look at our update method and what one pixel is doing, we'll realize: we're starting from the first pixel, and if it can fall, it swaps with the pixel below it. That means, we'll actually see that pixel again later and apply its rule again! This means, in a single pass of the list of particles, a particle could get to the bottom of the screen!
This is one of the most common falling sand simulation bugs: update order accidentally lets the same particle move more than once per frame.
Fortunately, it's an easy fix - we just start from the end!
update() {
// Draw from the end of the list to the beginning
for (let i = this.grid.length - this.width - 1; i > 0; i--) {
this.updatePixel(i);
}
}
Trying drawing again - you should see the particles falling now!
Can we always iterate from back to front? (What if our particle was smoke?)
This is why grid-based simulations often need different update strategies for different materials: sand falls down, smoke rises, and fluids may spread sideways.
Our sand doesn't really look like sand still - it's making little towers, which is neat, but not what we want.
It's time for rule #2!
Settling behavior for sand particles
Consider the way sand behaves. It doesn't just fall straight down - it'll roll to the side and down if there's space to. We need to integrate this into our system.
We need to check not only directly below, but below and to the left, and below and to the right.
These three checks form the basic falling sand algorithm: down first, then diagonal movement when the direct path is blocked.
updatePixel(i) {
// Get the indices of the pixels directly below
const below = i + this.width;
const belowLeft = below - 1;
const belowRight = below + 1;
// If there are no pixels below, including diagonals, move it accordingly.
if (this.isEmpty(below)) {
this.swap(i, below);
} else if (this.isEmpty(belowLeft)) {
this.swap(i, belowLeft);
} else if (this.isEmpty(belowRight)) {
this.swap(i, belowRight);
}
}
If we try drawing on the canvas, we can see that the sand properly settles now, instead of making little towers!
How might this rule differ for some other materials - like water or smoke?
Some final polish
We're just about done! But let's add some final touches.
We can improve the experience of adding sand by drawing a filled circle, instead of a single granule, when we interact with the canvas. We can make it feel even a bit more natural by aerating it a bit- that is, only drawing each granule with some probability.
p.onLeftClick = (x, y) => {
grid.setCircle(
x,
y,
() => varyColor(p, SAND_COLOR), // Color
2, // Radius
0.5 // Probability
);
};
And we've arrived at the same canvas that we saw at the very beginning!
That's it for now! If this was interesting, feel free to reach out to me! My hope is that you now have a foundation to build on, whether you're making a falling sand game, or another project that incorporates particle (and especially gravity-based) interactions. I'm considering making this a series, highlighting different materials and the emergent behavior that can arise. Another aspect is performance. Our current approach will not scale very well, but there are both lower-level approaches and tricks we can use to improve it!
Questions this post answers
How does a falling sand simulation work?
A falling sand simulation stores materials in a 2D grid and updates each particle with local rules. Sand checks the cell below, moves down if it is empty, and slides diagonally when blocked.
How do you build a falling sand simulation in JavaScript?
You create a grid, place particles into cells, update those particles every animation frame, and draw the grid to a canvas. This post uses p5.js to keep the browser rendering simple.
Why did the sand instantly fall to the bottom?
The first update loop processed a particle more than once in a single frame. Reversing the update order prevents a particle from repeatedly moving downward during the same pass.
What rules make sand settle naturally?
The basic rule checks below first, then below-left and below-right. That lets particles fall, pile up, and slide down slopes instead of stacking into vertical towers.
(2022-05-15) Check out the next post in the series, Improving the foundation of our falling sand simulator!
Please note
Throughout the post, I only show the code critical for the functionality of the step. There's some abstraction on top of p5.js to keep everything as simple as possible, but all source code that I wrote is non-minified and available by looking at the source of this page. There are library functions and there is step-specific code.