Learning p5.js week two: Marching Squares

This week's experiment dives into the marching squares algorithm, following this video from The Coding Train.

What are Marching Squares #

According to Wikipedia:

[...] an algorithm that generates contours for a two-dimensional scalar field (rectangular array of individual numerical values)

In simpler terms, it’s a way to turn a field of numbers into shapes. Its 3D cousin, marching cubes, is often used in game development to build procedural worlds — think Minecraft or Terraria.

If you're curious about how that looks in practice, Sebastian Lague’s video is a great deep dive into generating landscapes on the fly.

How It Works #

The script builds a grid of cells across the canvas like a chessboard, and assigns each corner a value based on a noise function.

Each square is then evaluated: depending on which corners are above or below a threshold, a contour line is drawn through it. The result is a fluid, organic network of lines that seem to outline invisible terrain.

It's a surprisingly compact algorithm for what it does. With just a few loops and a bit of logic, a world starts to take shape from numbers alone.

Final result #

References #