Recursive AI

Carve destructible 2D terrain in C#

OnePhysics is a free, open-source physics library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Carve craters in a 2D collision surface from a grid of solid and empty cells. Detached patches can become falling rigid bodies.

Terminal
dotnet add package RecursiveAI.OnePhysics

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OnePhysics.Physics2D;
 
var world = new PhysicsWorld2D();
var solid = new bool[16 * 8];
Array.Fill(solid, true);
var ground = world.AddBitmaskTerrain(
    16, 8, solid);
ground.CarveCircle(new(8, 8), 3);
Console.WriteLine("Crater carved.");
Text
Crater carved.

Unzip the example, then dotnet run.

The full program

The program builds the floor and an isolated patch in memory, rests a box on the floor, then removes its support. No input files are needed.

C#
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics2D;
 
var world = new PhysicsWorld2D();
var solid = new bool[32 * 16];
for (int y = 0; y < 8; y++)
    for (int x = 0; x < 32; x++) solid[y * 32 + x] = true;
// An isolated patch above the floor, ready to detach.
for (int y = 12; y < 14; y++)
    for (int x = 24; x < 28; x++) solid[y * 32 + x] = true;
var ground = world.AddBitmaskTerrain(32, 16, solid, cellSize: 0.5f);
var box = world.AddBox(new(0.5f, 0.5f), at: new(4, 4.5));
for (int i = 0; i < 120; i++) world.Step(1f / 60);
Console.WriteLine($"Before carve: y={box.Position.Y:F2}");
byte[] before = world.Snapshot();
ulong EditAndStep()
{
    ground.CarveCircle(new(4, 4), 1.5);
    var islands = ground.DetachIslands();
    Console.WriteLine($"Detached islands: {islands.Length}");
    for (int i = 0; i < 60; i++) world.Step(1f / 60);
    Console.WriteLine($"After carve: y={box.Position.Y:F2}");
    return world.ComputeHash();
}
ulong first = EditAndStep();
world.Restore(before);
Console.WriteLine($"Restored edit:");
ulong second = EditAndStep();
Console.WriteLine($"Repeated hash matches: {first == second}");

dotnet run prints:

Text
Before carve: y=4.25
Detached islands: 1
After carve: y=2.75
Restored edit:
Detached islands: 1
After carve: y=2.75
Repeated hash matches: True

Variations

Refill a crater. Append this to the snippet at the top:

C#
ground.FillPolygon([new(5, 5), new(11, 5),
    new(11, 8), new(5, 8)]);
Console.WriteLine("Crater refilled.");

The additional line is:

Text
Crater refilled.

The short answer

Create a bool[] describing solid ground, pass it to AddBitmaskTerrain, and edit the returned body with CarveCircle. OnePhysics updates the collision boundary, not a screen image. Your application supplies the drawing. Use DetachIslands when disconnected ground should become dynamic bodies rather than remain part of the terrain.

The example uses two separate operations deliberately. Carving changes which cells are solid; detaching finds pieces no longer connected to the anchors and turns them into bodies. You can carve several times before asking for the detached pieces. The returned array is the set of new bodies, in piece order, rather than a replacement handle for all the ground.

How do you make destructible 2D terrain in C#?

Start with the occupancy grid. Index it as y * width + x: x changes fastest, and true means ground. In the full program the bottom half of the grid is solid, with a separate patch higher up. Cell size is 0.5 world units, so the filled lower rows form a floor at about y = 4. The box starts just above that surface and is allowed to settle before the edit.

This is a sampled contour, not one collider box per visible pixel. Each solid cell contributes a sample at its center. OnePhysics uses marching squares to build the boundary between solid and empty samples. A circular edit therefore changes a contour rather than producing a staircase of individual square colliders. Choose cell size according to the smallest terrain detail that must affect collisions; it is a geometry input, not a rendering resolution setting.

Call CarveCircle with the crater center and radius in world coordinates. In contrast, the array dimensions describe cells. Keep those units separate when mapping a mouse click or an explosion to the terrain. The snippet at the top creates its own data so it can run without an image importer or game editor.

The full program shows what removing support does. Before the carve the box rests at y = 4.25. After stepping the edited world it rests at y = 2.75, lower in the crater. An edit rebuilds the boundary near the changed cells and wakes nearby bodies so they can find the new surface. Segments outside that rebuild retain their handles and cached contacts; bodies far from the edit are not woken. This is local editing, not a promise that every body on a long segment will keep exactly the same arithmetic after that segment is shortened.

FillPolygon puts material back. The variation fills a rectangular region across the crater. It changes the same terrain body, so there is no second terrain object to swap into the world. Use the collision data as the authority for your drawing, or apply the same edits to your own visual representation.

DetachIslands keeps pieces touching the bottom row by default, the terrain’s anchors. The isolated upper patch in the full program touches no anchor and becomes one dynamic body. Detached pieces are covered by boxes; they are not arbitrary visual meshes. Keep that representation in mind if very thin or irregular fragments are important to your game.

Terrain edits are included in snapshots, world hashes, replays and forks. The full program saves a snapshot before carving, restores it and applies the same edit and fixed steps again. The two resulting hashes match in the shown run. Restore before replaying edits, and keep the edit order and step size the same; a seed is not needed for this circular terrain operation. See the terrain guide for the public terrain API.

All onephysics recipes