Recursive AI

Simulate pouring water in a 2D C# game

onegame is a free, open-source game engine for .NET from Recursive AI. MIT or Apache-2.0, no editor required.

Fill a box with water particles above a solid circle. Step the world to let gravity carry the water around it.

Terminal
dotnet add package RecursiveAI.OneGame.Physics

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

C#
using OneGame.Core;
using OneGame.Physics;
 
// 9 is the simulation seed.
var world = new World(9, new EntityRegistry());
var space = PhysicsSpace2D.AddTo(world);
space.AddCircle(Fixed.One, new FVec2(0, 0),
    new BodyOptions { Kind = BodyKind.Static });
var water = space.AddFluid();
space.FillFluidBox(water, new FVec2(-1, 2),
    new FVec2(1, 3));
for (int tick = 0; tick < 90; tick++) world.Step();
 
var min = new FVec2(-20, -20);
var max = new FVec2(20, -1);
Console.WriteLine(space.OverlapFluidBox(
    min, max, default, water));

Prints how many particles the box query finds below the circle:

Text
170

Unzip the example, then dotnet run.

The full program

The water starts in the rectangle from (-1, 2) to (1, 3); the obstacle is a stationary circle of radius 1 at the origin. No images or scene files are needed. The program runs 90 simulation ticks and counts the particles below the circle separately on each side.

C#
using OneGame.Core;
using OneGame.Physics;
 
var world = new World(9, new EntityRegistry());
var space = PhysicsSpace2D.AddTo(world);
space.AddCircle(Fixed.One, new FVec2(0, 0),
    new BodyOptions { Kind = BodyKind.Static });
var water = space.AddFluid();
space.FillFluidBox(water, new FVec2(-1, 2),
    new FVec2(1, 3));
for (int tick = 0; tick < 90; tick++) world.Step();
 
var particles = new FluidParticle[space.ParticleCount(water)];
int count = space.GetFluidParticles(particles, water);
int belowLeft = 0, belowRight = 0;
foreach (var particle in particles.AsSpan(0, count))
{
    if (particle.Position.Y >= -1) continue;
    if (particle.Position.X < 0) belowLeft++;
    else belowRight++;
}
Console.WriteLine($"Water particles: {count}");
Console.WriteLine($"Below the circle, left: {belowLeft}");
Console.WriteLine($"Below the circle, right: {belowRight}");
Text
Water particles: 200
Below the circle, left: 84
Below the circle, right: 86

If a collider seems to have no effect, check that the collider and the water are in the same PhysicsSpace2D, and that you’ve stepped its world before reading positions.

Variations

For a stream instead of a single pour, replace FillFluidBox in the full example with an emitter above the circle. This nozzle points down and stops after emitting at most 60 particles.

C#
space.AddEmitter(water, new FluidEmitterOptions
{
    Position = new FVec2(0, 3),
    Direction = new FVec2(0, -1),
    Speed = 3,
    MaxEmitted = 60
});

The short answer

Create a PhysicsSpace2D, add a static collider and register water with AddFluid(). Fill a box above the collider, then step the world. A box query can tell you how much of the pour reached a region; GetFluidParticles gives you individual positions for drawing or counting.

How do you simulate flowing water in a 2D game?

Use an initial fill when the scene starts with a known amount of water, such as a bucket that’s already full. Use an emitter when water enters over several ticks, such as a faucet that can stay on while the player moves a container. A filled box and an emitter both feed the same fluid, so the same query can count either one. The OneGame fluid guide also describes drains for removing water after it reaches a region.

Put the fluid and obstacles into the space during world setup. The sample calls world.Step() explicitly because it runs without a game window. In a hosted game the world tick steps the installed physics space; don’t step it again from the drawing code. Use fixed-point positions (Fixed and FVec2) in the simulation and read the results from your view.

How do you draw and track water particles in a 2D game?

In a windowed OneGame project, put this in an IView2D entity with a synced FluidRef Water set to the handle returned by AddFluid(). Import System.Numerics, OneGame.Host, OneGame.Physics, and OneGame.UI. The buffer fits this example’s 200 particles. The negative Y converts from physics coordinates (up is positive) to drawing coordinates (down is positive).

C#
private readonly FluidParticle[] particles = new FluidParticle[200];
 
[View]
public void Draw(Draw2D d)
{
    if (PhysicsSpace2D.Of(World!) is not { } space) return;
    int count = space.GetFluidParticles(particles, Water);
    const float pixelsPerUnit = 24;
    for (int i = 0; i < count; i++)
    {
        var position = particles[i].Position;
        var center = new Vector2(
            position.X.ToSingle() * pixelsPerUnit,
            -position.Y.ToSingle() * pixelsPerUnit);
        d.FillCircle(center, 2, Color.Rgb(0x3b8fe0));
    }
}

Particle order can change across ticks. If the view tracks a particle between frames, use its Id, not its position in the array.

Choose between reading particles and asking a smaller question about the scene. To tell whether water has reached a cup, query the space in the cup’s area. You can pass default for the output buffer if you only need the count, as in the snippet at the top. Use ParticleCount when the region doesn’t matter. The sample’s total hasn’t gone down; the particles not included in the two counts are outside the measured region, not removed by a drain.

All fluids in a space share the same particle spacing. Smaller spacing puts more particles into the same fill area. Choose a particle budget and spacing for the smallest detail that matters to the scene, then check that pours and pools still behave as intended in your actual level.

All onegame recipes