Skip to content

Commit

Permalink
Fix Time inconsistency after substepping loop (#294)
Browse files Browse the repository at this point in the history
# Objective

There are currently two issues that cause `Time` to be inconsistent, even with a fixed timestep:

1. After the substepping loop, the `Time` resource is always set to `Time<Virtual>`. However, the `PhysicsSchedule` is still running. This means that systems running after substeps but before the end of the physics schedule will have a variable `Time`.
2. After the `PhysicsSchedule`, `Time` is set to `Time<Virtual>`. This means that if physics is run in `FixedUpdate`, the fixed timestep will be overwritten by `Time<Virtual>`.

## Solution

1. Set `Time` to `Time<Physics>` instead. The physics schedule will later set it to the default clock.
2. Set `Time` to the clock that was used before the `PhysicsSchedule`.
  • Loading branch information
Jondolf authored Jan 5, 2024
1 parent 2211784 commit f76ba08
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/plugins/setup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ fn run_physics_schedule(world: &mut World, mut is_first_run: Local<IsFirstRun>)
let real_delta = world.resource::<Time<Real>>().delta();
let old_delta = world.resource::<Time<Physics>>().delta();
let is_paused = world.resource::<Time<Physics>>().is_paused();
let old_clock = world.resource::<Time>().as_generic();
let physics_clock = world.resource_mut::<Time<Physics>>();

// Get the scaled timestep delta time based on the timestep mode.
Expand Down Expand Up @@ -276,12 +277,12 @@ fn run_physics_schedule(world: &mut World, mut is_first_run: Local<IsFirstRun>)
.resource_mut::<Time<Physics>>()
.advance_by(Duration::ZERO);
}

// Set generic `Time` resource back to the clock that was active before physics.
*world.resource_mut::<Time>() = old_clock;
});

is_first_run.0 = false;

// Set generic `Time` resource back to `Time<Virtual>`.
*world.resource_mut::<Time>() = world.resource::<Time<Virtual>>().as_generic();
}

/// Runs the [`SubstepSchedule`].
Expand All @@ -301,7 +302,9 @@ fn run_substep_schedule(world: &mut World) {
}
});

*world.resource_mut::<Time>() = world.resource::<Time<Virtual>>().as_generic();
// Set generic `Time` resource back to `Time<Physics>`.
// Later, it's set back to the default clock after the `PhysicsSchedule`.
*world.resource_mut::<Time>() = world.resource::<Time<Physics>>().as_generic();
}

/// Runs the [`PostProcessCollisions`] schedule.
Expand Down

0 comments on commit f76ba08

Please sign in to comment.