All projects
Project 02 · Unreal · C++, Python

Time to Breach

Role: Time Rewind System

Time to Breach is a CRPG where the player can rewind their own last few seconds while the enemies keep fighting in real time. I built the rewind system. It’s a real state rewind, not a visual effect: position, velocity, movement state and health all go back, and play resumes from wherever the rewind stops.

Time to Breach gameplay: a top-down fight between armoured soldiers among crates on a neon-lit floor

Project Overview

Project Type
CRPG
Role
Time Rewind System
Team Size
8 people
Duration
4 weeks
Engine
Unreal Engine 5
Language
C++, Python

Problem & Goal

Rewinding only the player is harder than rewinding the whole world. The enemies keep moving, so the game can’t just replay a recording of the level. The player’s own actor has to travel back through its history and then hand control back in the middle of a fight, with physics, animation and health all agreeing with each other.

The goals:

  • Smooth playback at any rewind speed, independent of frame rate.
  • Fixed, predictable memory, however long a session runs.
  • Reversible gameplay state, not just position: take damage, rewind, and the health comes back.
  • One component that works on any actor, not code tied to the player character.

How It Works

The component keeps two kinds of history. Continuous state (where the actor is and how it’s moving) is sampled into a ring buffer. Discrete changes, like taking damage, are logged as undo actions on a timeline.

  1. Record30 snapshots a second into a ring buffer
  2. RewindStep back, blending two snapshots each frame
  3. UndoRun the undo actions newer than the playback time
  4. ResumeDrop the old future and record from here

Motion is reversed by interpolating between snapshots.
Gameplay changes are reversed by undo actions.

Snapshot ring buffer

Thirty times a second the component stores a snapshot: a timestamp, the actor’s transform, and its linear and angular velocity. For characters it also stores the movement velocity and movement mode, which is what the animation blueprint reads, so the legs move correctly while rewinding. Frames where the actor hasn’t moved are skipped, so standing still doesn’t use up the buffer.

The buffer size comes from the longest rewind the game mode allows. Ten seconds at 30 Hz is 300 snapshots of about 200 bytes each: roughly 60 KB per rewindable actor, reserved once in BeginPlay. An ensure flags any setting that would need more than 1 MB (3 MB with animation data). When the buffer is full, the oldest snapshot is dropped. The component ticks in TG_PostPhysics, after movement has run, so each snapshot holds the frame’s final position.

void URewindComponent::RecordSnapshot(float DeltaTime)
{
    FTransform Transform = GetOwner()->GetActorTransform();
    if (!TransformAndVelocityRecentHistory.IsEmpty())
    {
        if (Transform.Equals(TransformAndVelocityRecentHistory.Last().Transform))
        {
            return;
        }
    }
    TimeSinceSnapshotsChanged += DeltaTime;

    LocalTimeFromStart += DeltaTime;

    // Early out if it's not yet time to record a snapshot
    if (TimeSinceSnapshotsChanged < SnapshotFrequencySeconds &&
        TransformAndVelocityRecentHistory.Num() != 0)
    {
        return;
    }

    // If the buffer is full, drop the oldest snapshot
    if (TransformAndVelocityRecentHistory.Num() == MaxSnapshots)
    {
        TransformAndVelocityRecentHistory.PopFront();
    }

    FVector LinearVelocity = OwnerRootComponent
        ? OwnerRootComponent->GetPhysicsLinearVelocity()
        : FVector::Zero();
    FVector AngularVelocityInRadians = OwnerRootComponent
        ? OwnerRootComponent->GetPhysicsAngularVelocityInRadians()
        : FVector::Zero();
    LatestSnapshotIndex = TransformAndVelocityRecentHistory.Emplace(
        LocalTimeFromStart, TimeSinceSnapshotsChanged, Transform,
        LinearVelocity, AngularVelocityInRadians);

    if (bSnapshotAnimationVariables && OwnerMovementComponent)
    {
        // If the buffer is full, drop the oldest snapshot
        if (AnimationRecentHistory.Num() == MaxSnapshots)
        {
            AnimationRecentHistory.PopFront();
        }

        // Record the movement velocity and movement mode
        FVector MovementVelocity = OwnerMovementComponent->Velocity;
        TEnumAsByte<EMovementMode> MovementMode =
            OwnerMovementComponent->MovementMode;
        int32 LatestMovementSnapshotIndex = AnimationRecentHistory.Emplace(
            LocalTimeFromStart, TimeSinceSnapshotsChanged,
            MovementVelocity, MovementMode);
        check(LatestSnapshotIndex == LatestMovementSnapshotIndex);
    }

    TimeSinceSnapshotsChanged = 0.0f;
}
Recording, from RewindComponent.cpp with the profiler scope and TODO notes removed. The animation buffer stays index-aligned with the transform buffer, and a check enforces it.

Playback

While rewinding, the component walks backwards through the buffer at DeltaTime × RewindSpeed. Each frame it finds the two snapshots on either side of the playback time and blends them: FTransform::Blend for the transform, a lerp for the velocities, and the movement mode switches at the halfway point. Physics simulation is paused for the duration so it can’t fight the playback.

A rewind can be open-ended, for as long as the input is held, or exact: LocalRewindSecondsAtSpeed rewinds a set number of seconds, clamped to the oldest snapshot, and the blend clamps to the stop time so the actor lands precisely on it. Two Blueprint functions return the path and the end position of a rewind without running it, so the game can show where a rewind would land before the player commits.

When the rewind stops, every snapshot newer than the stop point is erased and recording continues from there. The timeline branches instead of snapping back to the old future.

Undo timeline

Discrete changes aren’t sampled. When a system changes something reversible, it records an undo action: a closure that puts back the previous value, stamped with the current timeline time. During a rewind, every action newer than the playback time runs, newest first, and is then removed.

Health is the only system using it in the shipped game, and this is the whole integration:

void UGP_HealthComponent::SetCurrentHealth(float CurrentHealth)
{
    const auto NextHealth = FMath::Clamp(CurrentHealth, 0.0f, MaxHealth);
    const auto PreviousHealth = Health;
    Health = NextHealth;

    OnHealthChanged.Broadcast(PreviousHealth, NextHealth);
    if (RewindComponent)
    {
        TWeakObjectPtr<UGP_HealthComponent> WeakThis(this);
        RewindComponent->RecordEvent([WeakThis, PreviousHealth]()
        {
            if (WeakThis.IsValid())
            {
                WeakThis->RewindCurrentHealth(PreviousHealth);
            }
        });
    }
}
Every health change records how to undo itself. The weak pointer means an undo can never call into a destroyed component.

The timeline is a doubly linked list ordered by time: recording appends at the tail and rewinding pops from the tail, so both are constant time per event. Systems written in Blueprint get the same feature through RecordBPFloatEvent, which stores a delegate and the value to restore.

Editor tool: reversed animations (Python)

To check how animations read when played backwards, I wrote an Unreal Python script. Given a content folder, it duplicates every AnimSequence and AnimMontage in it into a mirrored _Rewind folder and sets each copy to play at −1 speed. It keeps the subfolder structure and skips assets that already exist, so it’s safe to run again after new animations are added.

anim_filters = unreal.ARFilter(
    class_names=["AnimSequence", "AnimMontage"],
    package_paths=[source_directory],
    recursive_paths=True
)
anim_assets = asset_registry.get_assets(anim_filters)

for asset_data in anim_assets:
    asset_path = asset_data.get_asset().get_path_name()
    asset = unreal.load_asset(asset_path)
    new_name = asset.get_name() + "_Rewind"
    # ... mirror the source subfolder under <source>_Rewind, skip existing assets ...

    new_asset = unreal.EditorAssetLibrary.duplicate_asset(
        asset_path,
        f"{target_directory}/{new_name}"
    )
    if isinstance(new_asset, unreal.AnimSequence):
        new_asset.set_editor_property("rate_scale", -1.0)
    elif isinstance(new_asset, unreal.AnimMontage):
        new_asset.set_editor_property("play_rate", -1.0)

    unreal.EditorAssetLibrary.save_loaded_asset(new_asset)
The core of the script, condensed: error handling and logging removed.

Results

  • Rewinds play back smoothly at any speed, because playback blends between snapshots instead of snapping to them.
  • Memory is fixed and known up front: about 60 KB per rewindable actor for the default ten-second window, and changing the window in the game mode resizes every buffer.
  • Damage taken inside the rewind window comes back with the motion, so position and health never disagree after a rewind.
  • Enemies and the rest of the world keep running while the player rewinds, which makes a rewind a tactical move rather than a pause.
  • The component isn’t tied to the player. Any actor can carry it, and the rewindable character base class switches on the extra animation data.

What I’d Change

  • Put more systems on the undo timeline. Ammo and status effects need nothing new, and the component already has a stubbed record type for Gameplay Ability System cooldowns.
  • Pool the undo actions. Each one is a heap-allocated list node holding a TFunction. That’s fine for health, but not for something that changes every frame.
  • Cover montage-driven actions. Firing and rolling play montages that don’t follow movement velocity, so they don’t line up with the reversed motion yet.
Time to Breach key art: an armoured soldier holding a rifle