# 8. Racing Capstone Best-Lap Ghost
Part of [[Racing Game Capstone]]. Back: [[7. Racing Capstone Cinemachine Chase and Finish Cameras]]. Next: [[9. Racing Capstone HUD Results and Best Times]].
> [!warning] Code not compiled in Unity
> `GhostCodec` (with the reused `PoseTrack`) was compiled and **run** (2 of the 25 tests in part 10). `LapGhostRecorder` and `LapGhostPlayer` were type-checked against Unity 6000.5.8f1. No ghost has been recorded or shown in a scene.
## 8.1 What is reused, and what is not
From [[Replays and Ghost Recording]]:
- **`PoseTrack`, unchanged.** It is the tested ring buffer with lerp/slerp evaluation (6 tests in [[2. A Pose Ring Buffer]]). The best lap is a `PoseTrack`.
- **The rules from [[1. Poses vs Input Events]]**: a ghost is a *pose* replay, not a second simulation; record the rendered pose in `LateUpdate`; sample at a fixed rate (30 Hz); never give the ghost a Rigidbody.
- **The costume rule from [[3. Ghost Playback]]**: the ghost is a mesh and a material at scene root, nothing else.
What this capstone does **not** reuse as-is, and why:
| Replays class | Clock | Problem in a race | Here instead |
|---|---|---|---|
| `PoseRecorder` | `Time.unscaledTime` | Pausing mid-lap keeps recording a parked car, so the ghost would stop for as long as you were in the pause menu | `LapGhostRecorder` samples on **lap time from the race clock** (scaled, so pause freezes it) |
| `GhostPlayer` | its own unscaled clock from `Play()` | Drifts from the player after any pause, and does not restart with each lap | `LapGhostPlayer` evaluates the track at the player's **current lap time** every frame |
Unscaled time is right for a kill-cam that plays *while* the game is paused. A lap ghost is the opposite: it must stop when the race stops. The Replays note already warns that a `timeScale` reset or a scaled/unscaled mix can push a sample back in time; keeping everything on one clock (the race clock) avoids that.
The ghost is also a **[[Game Programming Patterns (Review)]] Memento**: a snapshot of state you can play back without touching the thing it came from.
## 8.2 What "best lap ghost" means precisely
- Each lap, record the player car from `LapStarted` to `LapCompleted`, with sample times **relative to the lap start** (0 at the line).
- At `LapCompleted`, if the lap is faster than the current best, the recorded samples **become** the new best `PoseTrack` (a new object; the old one is never mutated while it is being played).
- The ghost shown during a lap is the best track evaluated at `raceTime - lapStart`. So it is always "where your best lap was at this moment of the lap". If you are ahead of it, it is behind you.
- Lap 1 starts at the green light from the grid, so a lap 1 ghost includes the standing start. Laps 2+ are flying laps and will almost always be the best.
## 8.3 GhostCodec (System.IO, tested)
A small binary format: magic `RGHO`, version, track id, lap time, sample count, then the eight floats `PoseTrack.Push` takes per sample. A 60 s lap at 30 Hz is 1800 samples x 32 bytes, about 58 KB. JSON of the same data would be several times larger and slower to parse.
The decoder rejects wrong magic, wrong version, a different track id (a ghost recorded on the old layout would drive through walls) and truncated files (tested).
```csharp
using System;
using System.Collections.Generic;
using System.IO;
namespace Racing
{
/// <summary>
/// Binary encode/decode for a best-lap ghost: a header (magic, version, track id,
/// lap time) and the same floats PoseTrack.Push takes. System.IO only, unit-tested.
/// </summary>
public static class GhostCodec
{
const uint Magic = 0x4F484752; // "RGHO" little-endian
const int Version = 1;
public static byte[] Encode(string trackId, float lapTime, IReadOnlyList<PoseTrack.Sample> samples)
{
using (var ms = new MemoryStream())
using (var w = new BinaryWriter(ms))
{
w.Write(Magic);
w.Write(Version);
w.Write(trackId ?? string.Empty);
w.Write(lapTime);
w.Write(samples.Count);
for (int i = 0; i < samples.Count; i++)
{
var s = samples[i];
w.Write(s.Time);
w.Write(s.Px); w.Write(s.Py); w.Write(s.Pz);
w.Write(s.Qx); w.Write(s.Qy); w.Write(s.Qz); w.Write(s.Qw);
}
w.Flush();
return ms.ToArray();
}
}
public static bool TryDecode(byte[] bytes, string expectedTrackId, out float lapTime,
out List<PoseTrack.Sample> samples)
{
lapTime = 0f;
samples = null;
if (bytes == null || bytes.Length < 16) return false;
try
{
using (var ms = new MemoryStream(bytes))
using (var r = new BinaryReader(ms))
{
if (r.ReadUInt32() != Magic) return false;
if (r.ReadInt32() != Version) return false;
string id = r.ReadString();
if (expectedTrackId != null && id != expectedTrackId) return false;
lapTime = r.ReadSingle();
int count = r.ReadInt32();
if (count < 2 || count > 1_000_000) return false;
samples = new List<PoseTrack.Sample>(count);
for (int i = 0; i < count; i++)
{
samples.Add(new PoseTrack.Sample
{
Time = r.ReadSingle(),
Px = r.ReadSingle(), Py = r.ReadSingle(), Pz = r.ReadSingle(),
Qx = r.ReadSingle(), Qy = r.ReadSingle(), Qz = r.ReadSingle(), Qw = r.ReadSingle()
});
}
return true;
}
}
catch (EndOfStreamException) { samples = null; return false; }
catch (IOException) { samples = null; return false; }
}
/// <summary>Builds a PoseTrack sized to the samples (no ring overwrite).</summary>
public static PoseTrack ToTrack(IReadOnlyList<PoseTrack.Sample> samples)
{
var track = new PoseTrack(Math.Max(2, samples.Count));
for (int i = 0; i < samples.Count; i++)
{
var s = samples[i];
track.Push(s.Time, s.Px, s.Py, s.Pz, s.Qx, s.Qy, s.Qz, s.Qw);
}
return track;
}
}
}
```
`ToTrack` sizes the `PoseTrack` to the sample count, so its ring never overwrites (a best lap must keep its first second).
## 8.4 LapGhostRecorder
Put it on the player car (or the `RaceManager` object) and assign the race, the player's `RacerProgress` and the car root as `target`.
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Racing
{
/// <summary>
/// Records the player's car every lap into PoseTrack samples keyed to LAP time (race clock,
/// so a pause does not leave a gap), keeps the fastest lap as the ghost, and saves it next to
/// the records file. Same LateUpdate fixed-rate sampling as the Replays note's PoseRecorder.
/// </summary>
public sealed class LapGhostRecorder : MonoBehaviour
{
[SerializeField] RaceManager race;
[SerializeField] RacerProgress racer;
[SerializeField] Transform target; // the car body root
[SerializeField] float samplesPerSecond = 30f;
[SerializeField] float maxLapSeconds = 600f;
[SerializeField] bool loadSavedGhost = true;
readonly List<PoseTrack.Sample> _current = new List<PoseTrack.Sample>(4096);
double _lapStart;
float _nextSample;
bool _recording;
public PoseTrack BestLap { get; private set; }
public float BestLapTime { get; private set; } = -1f;
/// <summary>Raised when a faster lap replaces the ghost.</summary>
public event Action<PoseTrack, float> BestLapChanged;
string GhostPath => Path.Combine(RaceRecords.Folder,
quot;ghost-{race.Track.TrackId}.bin");
void Start()
{
if (loadSavedGhost) TryLoad();
}
void OnEnable()
{
if (racer == null) return;
racer.LapStarted += OnLapStarted;
racer.LapCompleted += OnLapCompleted;
racer.Finished += OnFinished;
}
void OnDisable()
{
if (racer == null) return;
racer.LapStarted -= OnLapStarted;
racer.LapCompleted -= OnLapCompleted;
racer.Finished -= OnFinished;
}
void OnLapStarted(RacerProgress r, double lapStartTime)
{
_current.Clear();
_lapStart = lapStartTime;
_nextSample = 0f;
_recording = true;
SampleNow(0f);
}
void OnLapCompleted(RacerProgress r, float lapTime)
{
if (!_recording) return;
SampleNow(lapTime); // close the lap exactly on the line
_recording = false;
if (BestLapTime > 0f && lapTime >= BestLapTime) return;
if (_current.Count < 2) return;
BestLapTime = lapTime;
BestLap = GhostCodec.ToTrack(_current);
Save(lapTime);
BestLapChanged?.Invoke(BestLap, lapTime);
}
void OnFinished(RacerProgress r) => _recording = false;
void LateUpdate()
{
if (!_recording || target == null) return;
float lapTime = (float)(race.RaceTime - _lapStart);
if (lapTime > maxLapSeconds) { _recording = false; return; }
if (lapTime < _nextSample) return;
SampleNow(lapTime);
}
void SampleNow(float lapTime)
{
if (_current.Count > 0 && lapTime < _current[_current.Count - 1].Time) return;
Vector3 p = target.position;
Quaternion q = target.rotation;
_current.Add(new PoseTrack.Sample
{
Time = lapTime, Px = p.x, Py = p.y, Pz = p.z, Qx = q.x, Qy = q.y, Qz = q.z, Qw = q.w
});
_nextSample = lapTime + 1f / Mathf.Max(1f, samplesPerSecond);
}
void Save(float lapTime)
{
// Only overwrite the file when this beats the saved record too.
var rec = RaceRecords.Get(race.Track.TrackId);
if (rec != null && rec.bestLap > 0f && lapTime >= rec.bestLap && File.Exists(GhostPath)) return;
try
{
Directory.CreateDirectory(RaceRecords.Folder);
string tmp = GhostPath + ".tmp";
File.WriteAllBytes(tmp, GhostCodec.Encode(race.Track.TrackId, lapTime, _current));
if (File.Exists(GhostPath)) File.Replace(tmp, GhostPath, null);
else File.Move(tmp, GhostPath);
}
catch (Exception e)
{
Debug.LogWarning(quot;[Ghost] Could not save {GhostPath}: {e.Message}");
}
}
void TryLoad()
{
try
{
if (!File.Exists(GhostPath)) return;
if (!GhostCodec.TryDecode(File.ReadAllBytes(GhostPath), race.Track.TrackId, out float lap, out var samples))
return;
BestLapTime = lap;
BestLap = GhostCodec.ToTrack(samples);
BestLapChanged?.Invoke(BestLap, lap);
}
catch (Exception e)
{
Debug.LogWarning(quot;[Ghost] Could not load {GhostPath}: {e.Message}");
}
}
}
}
```
Details that matter:
- **Closing sample.** At `LapCompleted` it adds one final sample at exactly the lap time, so the ghost reaches the line at the right moment instead of up to 33 ms early.
- **No backwards time.** `SampleNow` refuses a time earlier than the last sample (`PoseTrack.Push` would throw).
- **Save policy.** The file is only overwritten when the lap also beats the saved record for this track. A slow session does not destroy a good ghost from yesterday.
- **Safe writes.** The ghost is written to `.tmp` and swapped in with `File.Replace` (or moved if there is no old file), the same idea as `AtomicFile` in [[High Scores, Saves and Player Stats]], in a bytes version.
- **Loading.** On `Start`, a saved ghost for this `trackId` becomes the best lap, so the first lap of a new session already has someone to chase.
- `maxLapSeconds` stops runaway recording if the player parks on the track for ten minutes.
Allocation: the sample list is pre-sized to 4096 and only grows on very long laps. `Add` of a struct does not allocate per sample.
## 8.5 LapGhostPlayer
```csharp
using UnityEngine;
namespace Racing
{
/// <summary>
/// Shows the best lap as a visual-only ghost, evaluated at the player's CURRENT lap time,
/// so it is always "where your best lap was at this moment of the lap". The ghost object is
/// a costume (mesh + translucent material) at scene root: no Rigidbody, colliders or scripts.
/// </summary>
public sealed class LapGhostPlayer : MonoBehaviour
{
[SerializeField] RaceManager race;
[SerializeField] RacerProgress racer;
[SerializeField] LapGhostRecorder recorder;
[SerializeField] Transform ghost;
[SerializeField] float hideAfterLapEnd = 0.5f;
double _lapStart;
bool _lapRunning;
void OnEnable()
{
if (racer != null) { racer.LapStarted += OnLapStarted; racer.Finished += OnFinished; }
}
void OnDisable()
{
if (racer != null) { racer.LapStarted -= OnLapStarted; racer.Finished -= OnFinished; }
}
void Start() => SetVisible(false);
void OnLapStarted(RacerProgress r, double lapStart)
{
_lapStart = lapStart;
_lapRunning = true;
}
void OnFinished(RacerProgress r)
{
_lapRunning = false;
SetVisible(false);
}
void LateUpdate()
{
var track = recorder != null ? recorder.BestLap : null;
if (!_lapRunning || track == null || ghost == null) { SetVisible(false); return; }
float t = (float)(race.RaceTime - _lapStart);
if (t > track.EndTime + hideAfterLapEnd) { SetVisible(false); return; }
if (!track.TryEvaluate(t, out var pose)) { SetVisible(false); return; }
ghost.SetPositionAndRotation(
new Vector3(pose.Px, pose.Py, pose.Pz),
new Quaternion(pose.Qx, pose.Qy, pose.Qz, pose.Qw));
SetVisible(true);
}
void SetVisible(bool visible)
{
if (ghost != null && ghost.gameObject.activeSelf != visible)
ghost.gameObject.SetActive(visible);
}
}
}
```
Ghost visual:
1. Duplicate the car's body and wheel meshes into a new `GhostCar` object at scene root. Delete every collider, Rigidbody, WheelCollider and script.
2. Layer `Ghost` (collides with nothing, part 1).
3. A URP Lit material with **Surface Type: Transparent**, alpha about 0.35, a cool tint, no shadows cast. Optionally a Fresnel rim in Shader Graph ([[URP Shaders and Shader Graph]]).
4. Assign it as `ghost` on `LapGhostPlayer`.
The wheels on the ghost do not spin or steer; the pose track only stores the body. That is normal for ghosts. If you want spinning wheels, record wheel rotation as extra channels: that means a second track type, not more fields on `PoseTrack`.
The ghost hides itself when there is no best lap yet, after the lap time passes the end of the best lap (you are slower than your best), and when the player finishes.
## 8.6 Exercise
1. Time trial setup: disable the AI cars, `totalLaps = 5`.
2. Lap 1: no ghost. Lap 2: the lap 1 ghost appears at the line and runs your lap 1 line.
3. Pause for ten seconds mid-lap, unpause: the ghost must be exactly where it was (race clock, not unscaled).
4. Restart the scene: the saved ghost is there on lap 1.
5. Change `trackId`, restart: no ghost (the old file is rejected).
Next: [[9. Racing Capstone HUD Results and Best Times]].