---
title: "Sync nearby physics objects to a multiplayer client in C#"
url: https://recursiveai.org/onephysics/cookbook/sync-nearby-physics-bodies-to-client/
description: "Sync nearby physics objects to a multiplayer client in C#. Send the initial state of a OnePhysics region, then send only what changes."
version: "1.3.0"
---

# Sync nearby physics objects to a multiplayer client in C#

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

[NuGet](https://www.nuget.org/packages/RecursiveAI.OnePhysics) · [GitHub](https://github.com/recursive-ai-oss/onephysics-csharp) · [Docs](https://recursiveai.org/onephysics/docs/) · [Download example (.zip)](https://recursiveai.org/onephysics/cookbook/sync-nearby-physics-bodies-to-client/sync-nearby-physics-bodies-to-client.zip)

Send each client updates for its interest region: the area it needs to simulate.

```shell
dotnet add package RecursiveAI.OnePhysics
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics2D;
var server = new PhysicsWorld2D();
server.AddCircle(0.5f, at: new(0, 5));
server.AddCircle(0.5f, at: new(10, 5));
var view = new InterestRegion().AddBox(
    new Vector2D(-2, 0), new Vector2D(2, 10));
var writer = server.CreateInterestWriter();
var client = new PhysicsWorld2D()
    .CreateInterestClient();
var message = writer.Write(view);
client.Apply(message);
Console.WriteLine(client.SharedBodyCount);
```

Prints `1`: only one of the server’s two circles is inside the client’s region.

Unzip [the example](https://recursiveai.org/onephysics/cookbook/sync-nearby-physics-bodies-to-client/sync-nearby-physics-bodies-to-client.zip), then `dotnet run`.

## The full program

Start with one circle visible, move the region so neither is inside, then move it over the other circle. The first message is a snapshot (the region’s initial state); later messages are deltas (changes since the previous message). The example passes message bytes directly between two worlds in one process. The client also has a local circle that stays in its world throughout.

```csharp
using RecursiveAI.OneMath;
using RecursiveAI.OnePhysics;
using RecursiveAI.OnePhysics.Physics2D;

var server = new PhysicsWorld2D();
server.AddCircle(0.5f, at: new(0, 5));
server.AddCircle(0.5f, at: new(10, 5));
var clientWorld = new PhysicsWorld2D();
clientWorld.AddCircle(0.5f, at: new(-20, 5)); // local, not streamed
var writer = server.CreateInterestWriter();
var client = clientWorld.CreateInterestClient();

InterestRegion Around(double x) => new InterestRegion().AddBox(
    new Vector2D(x - 2, 0), new Vector2D(x + 2, 10));

void Deliver(string label, InterestRegion region)
{
    byte[] message = writer.Write(region);
    client.Apply(message); // direct byte handoff in this example
    bool same = client.ComputeSharedHash() == server.ComputeInterestHash(region);
    Console.WriteLine($"{label}: shared {client.SharedBodyCount}, " +
        $"client total {clientWorld.BodyCount}, hashes match: {same}");
}

Console.WriteLine($"Server body count: {server.BodyCount}");
Deliver("Snapshot", Around(0));
server.Step(1f / 60);
Deliver("Delta", Around(5));  // neither circle is nearby
server.Step(1f / 60);
Deliver("Delta", Around(10)); // the other circle is now nearby
```

`dotnet run` prints:

```text
Server body count: 2
Snapshot: shared 1, client total 2, hashes match: True
Delta: shared 0, client total 1, hashes match: True
Delta: shared 1, client total 2, hashes match: True
```

If a client misses a message and can’t apply the next delta, `Apply` throws `InterestStreamException`; reset that client’s writer and send it a fresh snapshot.

## Variations

Send only bodies inside the region, without proxies (outside bodies that an inside body touches or hangs from). In the full program, replace the writer creation line with:

```csharp
var writer = server.CreateInterestWriter(
    new InterestOptions { Proxies = false });
```

The output is unchanged for these separate circles because they never touch or share a joint.

## Related recipes

- [Query physics bodies and filter by layer](https://recursiveai.org/onephysics/cookbook/queries-and-layers/)
- [Restore physics state and replay inputs](https://recursiveai.org/onephysics/cookbook/rollback/)

## The short answer

Create one `InterestWriter` per client on the server, and an `InterestClient` on each receiving world. `Write(region)` returns bytes to send over any reliable, ordered channel (such as TCP), and the client passes them to `Apply`. The first message seeds the client with a snapshot of that part of the world; later messages are deltas, meaning they describe what changed since the preceding message. Keep using the same writer for that client and deliver its messages in order, once each. `PhysicsWorld3D` has the same `CreateInterestWriter()` and `CreateInterestClient()` methods; use `Vector3D` corners for region boxes.

## How do you sync only nearby objects in a multiplayer game?

Build the region around the player or camera, and pass the current region on each write. OnePhysics includes a dynamic or kinematic body when its position is inside a region box or when it is explicitly named with `AddBody`. This isn’t a test for the shape overlapping the box. Static bodies don’t qualify by position alone. For example, ground can arrive as a static proxy when a body inside the region touches it. An outside dynamic body that arrives as a proxy is kinematic on the client, so the client’s solver doesn’t push it.

The stream creates bodies when they enter the region and removes them when they leave. The client can hold bodies of its own, as the full program shows. Don’t destroy the streamed bodies directly; they belong to the stream. Some features, including bodies with attached ropes or cables, are skipped; check `writer.LastSkipped` if you expected a body to arrive. See [the partial worlds guide](https://recursiveai.org/onephysics/docs/interest/) for details.

## What happens if a multiplayer client falls out of sync?

A delta depends on its predecessor. If a message can’t be recovered, reset the writer and send a new snapshot rather than trying to apply subsequent deltas to the old state. On initial connection or resync, keep the new snapshot and its following deltas in the same ordered message flow.

To check that the shared bodies agree, compare `ComputeSharedHash()` on the client with `ComputeInterestHash(region)` for the server state that produced the message. Compare immediately after applying the message, before the client advances its simulation. This is not a hash of the whole world: local bodies, proxies, contacts, joints, and sleep state are outside the comparison. The client can step ahead for prediction, but the next message restores the streamed state before applying the new changes.
