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!

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.

In this post, we'll just implement the most basic material, "sand".

This will be the final product for this post (drag around inside!):

Let's get started!

Drawing pixels 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.

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.

// 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

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.

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++) {

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

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!

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--) {

Trying drawing again - you should see the particles falling now!

Can we always iterate from back to front? (What if our particle was smoke?)

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

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.

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) => {
      () => 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! 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!

(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.