README
Falling Sand
A browser-based falling sand simulation built with p5.js.
Features
- Falling sand physics — grains fall, pile up, and slide diagonally around obstacles
- Mouse momentum — flick the mouse while painting to launch sand with real velocity; grains arc under gravity and bounce off walls before settling
- Cursor push — move the cursor over existing sand (without clicking) to push grains out of the way
- Random lifetimes — each grain lives for 10–30 seconds then fades smoothly into the background
- Rainbow colours — hue cycles continuously so each stroke is a different colour
- Mobile / touch support — paint and push with your fingers; multi-touch supported with per-finger velocity
- Pixel rendering — uses p5.js
pixels[]directly for fast rendering instead of individual shape calls
Controls
| Input | Action |
|---|---|
| Click & drag | Paint sand |
| Flick mouse while dragging | Launch sand with momentum |
| Move cursor over sand | Push grains away |
| Touch & drag (mobile) | Paint sand with finger |
| Flick finger while dragging | Launch sand with momentum |
Tunable constants
All physics and visual settings live at the top of sketch.js:
| Constant | Default | Description |
|---|---|---|
w |
5 |
Grain size in pixels |
MIN_LIFE |
600 |
Minimum grain lifetime (frames) |
MAX_LIFE |
1800 |
Maximum grain lifetime (frames) |
FADE_FRAMES |
60 |
Frames spent fading out before death |
GRAVITY |
0.25 |
Downward acceleration (cells/frame²) |
DAMPING_X |
0.88 |
Horizontal friction multiplier per frame |
MAX_V |
8 |
Maximum speed (cells/frame) |
V_SCALE |
0.5 |
Mouse drag speed → spawn velocity scale |
PUSH_RADIUS |
5 |
Cursor push field radius (cells) |
PUSH_STRENGTH |
1.5 |
Cursor push impulse strength |
MOUSE_BRUSH |
1 |
Paint brush radius for mouse (cells) |
TOUCH_BRUSH |
2 |
Paint brush radius for touch (cells) |
Technical notes
- The grid is stored as flat typed arrays (
Uint32Arrayfor colour,Uint16Arrayfor lifetime,Float32Arrayfor velocity) which are double-buffered and swapped each frame — no heap allocation in the hot path - Flying grains (significant velocity) move via a Bresenham path walk; slow grains fall back to classic cellular-automaton sand physics so piles form naturally
pixelDensity(1)is set to ensure direct pixel writes map 1:1 to canvas pixels
Running
Open index.html in any modern browser — no build step required.