The Foundations of Digital Particle Simulations

Creating a falling sand simulation requires a shift in perspective from traditional object-oriented programming to a grid-based cellular automata (CA) model. Unlike standard animations where objects move freely in space, this simulation treats every pixel—or a small group of pixels—as a discrete cell with a specific state. Drawing inspiration from titles like Noita and web experiments like Sandspiel by Max Bittker, we utilize the p5.js library to manage a two-dimensional array representing the canvas.
Each cell in our grid contains a value: a zero indicates an empty space, while a non-zero value represents a grain of sand. The complexity of the simulation arises not from the particles themselves, but from the rules applied to these cells every frame. By iterating through the grid and evaluating the neighbors of each cell, we can recreate the behavior of physical matter.
To ensure the simulation runs smoothly, we must maintain a distinction between the current state of the grid and the state for the next frame. Modifying the grid while simultaneously reading from it can lead to unintended race conditions where a single grain of sand 'teleports' across multiple cells in a single frame. Therefore, we utilize a dual-grid system where calculations are performed on the current frame and results are stored in a buffer for the next generation.
- Initialize a 2D array to store cell states.
- Define a constant resolution (e.g., 10px squares) to balance detail and performance.
- Use nested loops to iterate through every column and row index.
- Assign state values based on user interaction or initial conditions.
Implementing Core Gravity and Movement Rules

The most fundamental rule of a falling sand simulation is vertical gravity. If a cell contains sand and the cell immediately below it is empty (state 0), the sand must move down. This is achieved by setting the current cell to empty and the target cell to sand in the next generation's grid. However, simple vertical gravity only results in stacks of single pixels that do not resemble real sand behavior.
To simulate the way sand forms piles and slopes, we introduce diagonal movement. If the cell directly below is occupied, the simulation checks the bottom-left and bottom-right neighbors. If one of these is empty, the grain slides into that spot. This transition from vertical-only logic to diagonal logic is what creates the characteristic 45-degree slopes seen in nature.
ここからが大事な
ポイントです
具体例・注意点・明日から使えるヒントを整理しています。
✨無料閲覧で全文 + 図解の完全版を3日間いつでも読み返せる
あなたの好きな動画も、
1分でAI要約
📚 お気に入り保存 + ✨ あなたの動画をAI要約
(無料登録10秒)
✏️ この記事で学べること
- ▸HSB
10秒で完了・パスワード作成不要
