# 5. Floating Origin
Part of [[Open-World Streaming]]. Previous: [[4. Streaming Cells with Addressables]]. Next: [[6. Open-World Level Design Tests and Pitfalls]].
> [!warning] Code not compiled in Unity
> `FloatingOrigin` and `FloatingOriginFixups` type-checked against 6000.5.8f1. The Cinemachine hook was checked against the Cinemachine **3.1.8** package source only. None of it was run.
## 5.1 Why
A `float` has 24 bits of mantissa, so its precision depends on its size:
| Distance from origin | Spacing between adjacent float values |
|---|---|
| 1 km (1,024 m) | ~0.12 mm |
| 8 km | ~1 mm |
| 32 km | ~4 mm |
| 100 km | ~8 mm |
A millimetre doesn't sound like much. But physics solvers, skinned meshes and camera-relative rendering all **subtract** nearby positions, and the error shows up as jitter: wobbling hands in VR, a car that buzzes at rest, z-fighting decals. In VR the head's tiny motions are exactly the scale that breaks first.
The cure: keep the player near (0, 0, 0). When they wander past a threshold, move **everything** back by the same amount, and remember the total in a `double`.
## 5.2 The component
```csharp
// Assets/Scripts/Streaming/FloatingOrigin.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// Keeps the focus (player or camera) near (0,0,0) so float precision stays good.
/// When the focus passes `threshold` metres from the origin on X or Z, every root object in the
/// managed scenes moves by -shift and the offset grows by +shift.
/// True world position (double) = Offset + transform.position.
/// Managed scenes: this object's own scene, DontDestroyOnLoad (if this object is in it), and any
/// scene passed to Place() (the streamer does that for each cell as it finishes loading).
/// </summary>
[DefaultExecutionOrder(1000)]
public sealed class FloatingOrigin : MonoBehaviour
{
[SerializeField] Transform focus;
[SerializeField, Min(10f)] float threshold = 1000f;
[Tooltip("Snap shifts to this grid so grid-aligned content and world-space shader patterns don't swim. Use the streaming cell size.")]
[SerializeField, Min(0f)] float snap = 256f;
public static double OffsetX { get; private set; }
public static double OffsetZ { get; private set; }
/// <summary>Raised after roots move. The argument is the delta that was added to every position.</summary>
public static event Action<Vector3> Shifted;
static readonly HashSet<Scene> s_managed = new HashSet<Scene>();
readonly List<GameObject> _roots = new List<GameObject>(64);
readonly List<Scene> _scenes = new List<Scene>(16);
public static void WorldXZ(Vector3 local, out double x, out double z)
{
x = OffsetX + local.x;
z = OffsetZ + local.z;
}
/// <summary>
/// For a scene authored at true world coordinates that just finished loading: move its roots
/// into the current shifted frame, then manage it so future shifts move it too. Call once per load.
/// </summary>
public static void Place(Scene scene, List<GameObject> scratch)
{
if (!scene.IsValid() || s_managed.Contains(scene))
return;
if (OffsetX != 0d || OffsetZ != 0d)
MoveRoots(scene, new Vector3((float)-OffsetX, 0f, (float)-OffsetZ), scratch);
s_managed.Add(scene);
}
/// <summary>Call before (or right after) unloading a placed scene.</summary>
public static void Forget(Scene scene) => s_managed.Remove(scene);
static void MoveRoots(Scene scene, Vector3 delta, List<GameObject> scratch)
{
scratch.Clear();
scene.GetRootGameObjects(scratch);
for (var i = 0; i < scratch.Count; i++)
scratch[i].transform.position += delta;
}
void Awake() => s_managed.Add(gameObject.scene);
void LateUpdate()
{
if (focus == null)
return;
var p = focus.position;
if (Mathf.Abs(p.x) < threshold && Mathf.Abs(p.z) < threshold)
return;
var sx = snap > 0f ? Mathf.Round(p.x / snap) * snap : p.x;
var sz = snap > 0f ? Mathf.Round(p.z / snap) * snap : p.z;
var delta = new Vector3(-sx, 0f, -sz);
_scenes.Clear();
_scenes.AddRange(s_managed);
var own = gameObject.scene; // becomes the DontDestroyOnLoad scene if this object was moved there
if (!s_managed.Contains(own))
_scenes.Add(own);
for (var s = 0; s < _scenes.Count; s++)
{
if (_scenes[s].IsValid() && _scenes[s].isLoaded)
MoveRoots(_scenes[s], delta, _roots);
}
OffsetX += sx;
OffsetZ += sz;
Physics.SyncTransforms();
Shifted?.Invoke(delta);
}
void OnDestroy()
{
s_managed.Clear();
OffsetX = 0d;
OffsetZ = 0d;
}
}
```
### Walkthrough
- **Only roots move.** Moving each scene's root GameObjects moves their whole hierarchies. Thousands of children cost one transform change per root.
- **Managed scenes.** It shifts its own scene, the hidden `DontDestroyOnLoad` scene when it lives there, and any scene handed to `Place`. Why not every loaded scene? A cell that finished loading this frame, between the streamer's `Update` and this `LateUpdate`, hasn't been placed yet. Shifting it here and placing it next frame would move it twice. `Place` is the single point where a scene enters the shifted frame.
- **Snapped shifts.** With `snap = 256` (the cell size), the offset is always a whole number of cells. Anything that samples **world** position, such as triplanar shaders, noise, or grid-aligned water, stays continuous. Those shaders should add the offset back in: pass `OffsetX/Z` as a global shader vector after each shift.
- **`Physics.SyncTransforms()`** pushes the moved transforms into the physics scene right away, so the next simulation step doesn't see stale colliders.
- **`[DefaultExecutionOrder(1000)]`** runs the check after normal `LateUpdate`s (including most camera follow scripts), so a frame never renders half-shifted.
- **Y isn't shifted.** Most open worlds are wide, not tall. If you fly to space, add Y the same way.
### Set it up
1. On `Streaming`, set **FloatingOrigin → Focus** to the player, **Threshold** to 1000 and **Snap** to 256.
2. Move the player to x = 1100. The next frame, everything jumps back by 1024: the player is at x ≈ 76, and `OffsetX` is 1024. Cells keep streaming correctly, because `CellStreamer` reads `WorldXZ`.
3. Show the offset on a debug HUD (or in [[In-Game Debug Console and Cheat Tools]]), so a tester can report true coordinates.
## 5.3 What a root shift doesn't fix
```csharp
// Assets/Scripts/Streaming/FloatingOriginFixups.cs
using UnityEngine;
/// <summary>
/// Things a root-transform shift doesn't fix by itself: world-space particles and trails
/// keep their points in world coordinates. Put this on any object that has them.
/// </summary>
public sealed class FloatingOriginFixups : MonoBehaviour
{
[SerializeField] ParticleSystem[] worldSpaceParticles;
[SerializeField] TrailRenderer[] trails;
ParticleSystem.Particle[] _particles;
Vector3[] _points;
void OnEnable() => FloatingOrigin.Shifted += OnShifted;
void OnDisable() => FloatingOrigin.Shifted -= OnShifted;
void OnShifted(Vector3 delta)
{
if (worldSpaceParticles != null)
{
foreach (var ps in worldSpaceParticles)
{
if (ps == null || ps.main.simulationSpace != ParticleSystemSimulationSpace.World)
continue;
var max = ps.main.maxParticles;
if (_particles == null || _particles.Length < max)
_particles = new ParticleSystem.Particle[max];
var n = ps.GetParticles(_particles);
for (var i = 0; i < n; i++)
_particles[i].position += delta;
ps.SetParticles(_particles, n);
}
}
if (trails != null)
{
foreach (var trail in trails)
{
if (trail == null)
continue;
var n = trail.positionCount;
if (_points == null || _points.Length < n)
_points = new Vector3[Mathf.NextPowerOfTwo(Mathf.Max(n, 16))];
trail.GetPositions(_points);
for (var i = 0; i < n; i++)
_points[i] += delta;
trail.SetPositions(_points);
}
}
}
}
```
| System | Problem after a shift | Fix |
|---|---|---|
| World-space `ParticleSystem` | Live particles stay at the old world position | `GetParticles`, add delta, `SetParticles` (above) |
| `TrailRenderer` / `LineRenderer` in world space | A long streak to the old position | Shift the points (above), or `trail.Clear()` |
| Interpolated `Rigidbody` | One frame of streaking between the old and new pose | Usually invisible at 50+ Hz. If not, set `rb.interpolation = None` for one step around the shift |
| `NavMeshAgent` | Agent's internal position and path are stale | Bake per-cell NavMesh surfaces (they move with their scenes) and call `agent.Warp(agent.transform.position)` on `Shifted` |
| Cinemachine damping | Camera "flies" from the old position over its damping time | Tell Cinemachine the target was warped (below) |
| Anything caching a `Vector3` world position | Points at the old place | Subscribe to `FloatingOrigin.Shifted` and add the delta |
| Audio, `AudioSource` with Doppler | A Doppler blip from the sudden move | Usually negligible. Set Doppler to 0 on fast-moving sources |
### Cinemachine 3.1.8 hook
```csharp
// Assets/Scripts/Streaming/CinemachineOriginShift.cs
// Signature checked against the Cinemachine 3.1.8 package source (CinemachineCore.cs); not compiled here.
using Unity.Cinemachine;
using UnityEngine;
public sealed class CinemachineOriginShift : MonoBehaviour
{
[SerializeField] Transform followTarget;
void OnEnable() => FloatingOrigin.Shifted += OnShifted;
void OnDisable() => FloatingOrigin.Shifted -= OnShifted;
void OnShifted(Vector3 delta)
{
if (followTarget != null)
CinemachineCore.OnTargetObjectWarped(followTarget, delta);
}
}
```
`OnTargetObjectWarped` tells every Cinemachine camera following that target to move its internal state by the same delta. Then damping doesn't treat the jump as motion. See [[Cinemachine 3]] for the camera setup.
## 5.4 Multiplayer note
Each client can have its own floating origin. It's a *rendering and physics* convenience. Networked positions should travel as **true world** coordinates (doubles, or a cell index plus a local float offset). Never send shifted local positions, because two clients' offsets differ. See [[Multiplayer with Netcode for GameObjects]].
## 5.5 Pattern note
`Shifted` is an *Observer* ([[Game Programming Patterns (Review)]]). The origin doesn't know who cares; each system subscribes and fixes itself. The alternative, a central list of "things to fix", rots as soon as someone adds a new world-space effect and forgets to register it. The event version also rots, just more slowly, so part 6 adds a test-scene checklist.