Skip to content

Commit

Permalink
Fixes Timer Precision Error Causing Panic (#2362)
Browse files Browse the repository at this point in the history
# Objective

Fixes #2361 

## Solution

Uses integer division instead of floating-point which prevents precision errors, I think.
  • Loading branch information
jacobgardner committed Jun 26, 2021
1 parent b8f3d9c commit 52e8a19
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion crates/bevy_core/src/time/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,8 @@ impl Timer {

if self.finished() {
if self.repeating() {
self.times_finished = self.percent().floor() as u32;
self.times_finished =
(self.elapsed().as_nanos() / self.duration().as_nanos()) as u32;
// Duration does not have a modulo
self.set_elapsed(self.elapsed() - self.duration() * self.times_finished);
} else {
Expand Down Expand Up @@ -464,4 +465,20 @@ mod tests {
t.tick(Duration::from_secs_f32(0.5));
assert_eq!(t.times_finished(), 0);
}

#[test]
fn times_finished_precise() {
let mut t = Timer::from_seconds(0.01, true);
let duration = Duration::from_secs_f64(1.0 / 3.0);

t.tick(duration);
assert_eq!(t.times_finished(), 33);
t.tick(duration);
assert_eq!(t.times_finished(), 33);
t.tick(duration);
assert_eq!(t.times_finished(), 33);
// It has one additional tick this time to compensate for missing 100th tick
t.tick(duration);
assert_eq!(t.times_finished(), 34);
}
}

0 comments on commit 52e8a19

Please sign in to comment.