Recursive AI

Move rigid bodies between physics worlds in C#

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

Extract the bodies, then insert them into a world that uses the same length unit. ExtractBodies returns a packet with the bodies, their shapes, and supported joints and contacts. ToArray() turns it into bytes.

Terminal
dotnet add package RecursiveAI.OnePhysics

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

C#
using RecursiveAI.OnePhysics.Physics3D;
var source = new PhysicsWorld3D();
var target = new PhysicsWorld3D();
var ball = source.AddSphere(0.5f);
var packet = source.ExtractBodies([ball]);
var map = target.InsertBodies(packet);
var moved = target.GetBody(map.NewBodies[0]);
Console.WriteLine(moved.IsValid);

Prints True: the ball is accessible by its new handle.

Unzip the example, then dotnet run.

The full program

Move a crate and a ball into a world that already contains a body. This version round-trips the packet through bytes and pairs each old handle with its new one. The transfer order is based on the old body slots, not the order you passed to ExtractBodies.

C#
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics3D;
 
var source = new PhysicsWorld3D();
var crate = source.AddBox(new(1, 1, 1), at: new(0, 8, 0));
var ball = source.AddSphere(0.5f, at: new(6, 4, 0));
crate.LinearVelocity = new(3, 0, 0);
ball.LinearVelocity = new(-2, 0, 0);
 
// Keep the old handles and velocities before removing the bodies.
var handles = new[] { ball.RawHandle, crate.RawHandle };
var velocities = new[] { ball.LinearVelocity, crate.LinearVelocity };
var packet = source.ExtractBodies(new[] { ball, crate });
byte[] message = packet.ToArray();
 
var destination = new PhysicsWorld3D();
destination.AddSphere(0.5f, at: new(20, 4, 0)); // already occupied slot
var map = destination.InsertBodies(BodySetPacket.Read(message));
 
Console.WriteLine($"Source body count: {source.BodyCount}");
Console.WriteLine($"Destination body count: {destination.BodyCount}");
for (int i = 0; i < handles.Length; i++)
{
    var old = handles[i];
    // Old handles in a packet read from bytes have world ID 0.
    var wireHandle = new BodyHandle(0, old.Index, old.Generation);
    int index = map.OldBodies.IndexOf(wireHandle);
    if (index < 0) throw new InvalidOperationException("Missing body mapping.");
    var arrived = destination.GetBody(map.NewBodies[index]);
    bool sameVelocity = arrived.LinearVelocity.Equals(velocities[i]);
    Console.WriteLine($"{(i == 0 ? "Ball" : "Crate")} velocity preserved: {sameVelocity}");
}

dotnet run prints:

Text
Source body count: 0
Destination body count: 3
Ball velocity preserved: True
Crate velocity preserved: True

InsertBodies throws BodySetTransferException if it can’t insert the set, leaving the destination unchanged; extraction and insertion are separate operations, so that doesn’t put the moved bodies back in the source.

Variations

Copy the bodies instead of removing them. In the full program, replace the extraction line with:

C#
var packet = source.ExtractBodies(new[] { ball, crate },
    new BodySetOptions { Move = false });

The source count is now 2; the destination count and both velocity checks are unchanged.

The short answer

Call source.ExtractBodies(...) with the bodies you want to move, then pass the packet to destination.InsertBodies(...). In the same process you can pass the packet directly. If the receiver is elsewhere, send packet.ToArray() and reconstruct it with BodySetPacket.Read. In either case, InsertBodies returns parallel lists of old and new handles. Update any game objects that still refer to the original bodies before they next access physics.

Does moving a rigid body preserve its velocity?

Yes. With no transform, the body arrives at the same pose with its motion intact. This is useful for a handoff between regions where both worlds use the same coordinates. For a portal with different coordinates, insertion can translate and rotate the set: the rotation turns the velocity as well as the pose. In 2D, the transform takes a translation and an angle. The packet does not rescale between length units; the two worlds must agree on LengthUnit.

A packet also carries the set’s shapes, supported joints, and internal contacts with their solver state. A contact with a static body outside the set can carry over if the destination has the same static geometry at the same pose. If that geometry differs, the receiving world has to find the contact again on its next step. See moving bodies between worlds for supported body features and joint types.

How do you match old bodies to new bodies after a transfer?

For an in-memory packet, look up each original RawHandle in map.OldBodies and take map.NewBodies at the same index. If you read the packet from bytes, the old handles in the map have world ID zero. That’s why the full program looks up a handle with the same slot and generation but with world ID zero. Those lookup handles are keys into the map, not handles to use on either live world. If you’re processing packets from multiple worlds, keep track of which source sent each packet separately.

A joint with just one end in the set needs an explicit policy: transfer both endpoints, leave the joint behind with BoundaryPolicy.Break, or keep the outside endpoint as a shapeless anchor with BoundaryPolicy.HoldAsAnchor. When using anchors, only the first map.MemberCount entries represent members of the transferred set; the anchors follow them.

All onephysics recipes