Skip to content

Commit 543f66c

Browse files
committed
Add a new almost_finish method for Timer with immediate first tick
action Resolves #21860 This new method would tick the timer by `duration - 1 ns` leaving a very short waiting time for the first tick initiated by the user allowing immediate action.
1 parent b6bf94a commit 543f66c

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

crates/bevy_time/src/timer.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ pub struct Timer {
3636
duration: Duration,
3737
mode: TimerMode,
3838
finished: bool,
39+
almost_finished: bool,
3940
times_finished_this_tick: u32,
4041
}
4142

@@ -206,6 +207,21 @@ impl Timer {
206207
self.tick(remaining);
207208
}
208209

210+
/// Almost finishes the timer leaving 1 ns of remaining time.
211+
///
212+
/// # Examples
213+
/// ```
214+
/// # use bevy_time::*;
215+
/// let mut timer = Timer::from_seconds(1.5, TimerMode::Once);
216+
/// timer.almost_finish();
217+
/// assert!(!timer.is_finished());
218+
/// assert_eq!(t.remaining(), Duration::from_nanos(1));
219+
/// ```
220+
pub fn almost_finish(&mut self) {
221+
self.almost_finished = true;
222+
self.finish();
223+
}
224+
209225
/// Returns the mode of the timer.
210226
///
211227
/// # Examples
@@ -256,7 +272,7 @@ impl Timer {
256272
/// assert_eq!(timer.elapsed_secs(), 1.0);
257273
/// assert_eq!(repeating.elapsed_secs(), 0.5);
258274
/// ```
259-
pub fn tick(&mut self, delta: Duration) -> &Self {
275+
pub fn tick(&mut self, mut delta: Duration) -> &Self {
260276
if self.is_paused() {
261277
self.times_finished_this_tick = 0;
262278
if self.mode == TimerMode::Repeating {
@@ -270,6 +286,10 @@ impl Timer {
270286
return self;
271287
}
272288

289+
if self.almost_finished {
290+
delta -= Duration::from_nanos(1);
291+
self.almost_finished = false;
292+
}
273293
self.stopwatch.tick(delta);
274294
self.finished = self.elapsed() >= self.duration();
275295

@@ -628,6 +648,21 @@ mod tests {
628648
assert_eq!(t.times_finished_this_tick(), 34);
629649
}
630650

651+
#[test]
652+
fn almost_finished_repeating() {
653+
let mut t = Timer::from_seconds(10.0, TimerMode::Repeating);
654+
let duration = Duration::from_nanos(1);
655+
656+
t.almost_finish();
657+
assert!(!t.is_finished());
658+
assert_eq!(t.times_finished_this_tick(), 0);
659+
assert_eq!(t.remaining(), Duration::from_nanos(1));
660+
661+
t.tick(duration);
662+
assert!(t.is_finished());
663+
assert_eq!(t.times_finished_this_tick(), 1);
664+
}
665+
631666
#[test]
632667
fn paused() {
633668
let mut t = Timer::from_seconds(10.0, TimerMode::Once);

0 commit comments

Comments
 (0)