Simple Falling Sand Simulation

By: Lucas Sedberg

This is falling sand

Refresh the page or enable Javascript to see a falling sand simulation.

How to use

Move the mouse to place FallingSand. On mobile, hold and drag to place FallingSand. Clicking or tapping on the sand will remove it, and make sand fall in on itself.

How it works

The simulation

The simulation is divided into two types of particles: FallingSand and StaticSand. FallingSand represents a single pixel that moves down the canvas, and can converts to StaticSand when it stops moving. This approach allows us to only simulate the FallingSand, instead of every single pixel, including those at rest.

The sand particles follow these rules:

  • If there is no sand below, continue falling.
  • If there is sand below and to the right, move to the left.
  • If there is sand below and to the left, move to the right.
  • If there is sand below and to the left and right, move to the left or right randomly.
  • If there is sand below both sides, convert the FallingSand object to StaticSand, and remain in place.
  • If it is at the bottom of the canvas, convert the FallingSand object to StaticSand, and remain in place.

When you click or tap on the sand, sand in a ~5 pixel radius will be removed. Nearby StaticSand will convert to FallingSand, and start simulating again. It will also check for neighboring StaticSand that no longer have any sand below, and convert them to FallingSand.

The simulation is updated at 60 frames per second, and the canvas is cleared and redrawn each frame. It is also responsive, and will scale to fit the screen size.

The canvas

Using the HTML5 canvas element, we can draw and animate the simulation with Javascript/Typescript. The canvas is a 2D grid of pixels, and we can draw and manipulate each pixel individually. This allows us to create a simple and efficient simulation, that can run in the browser.

Source code

The source code for this simulation is not yet available. There may be some optimizations and improvements to be made before it is ready for release.

sand

Lucas Sedberg

Copyright © 2024 Lucas Sedberg

This website is currently under construction. Expect bugs, typos and inconsistencies.
Please check back later for updates and new content!