Skip to content

Commit 1382f97

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 1382f97

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

crates/bevy_time/src/timer.rs

Lines changed: 37 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,22 @@ 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+
/// use std::time::Duration;
216+
/// let mut timer = Timer::from_seconds(1.5, TimerMode::Once);
217+
/// timer.almost_finish();
218+
/// assert!(!timer.is_finished());
219+
/// assert_eq!(timer.remaining(), Duration::from_nanos(1));
220+
/// ```
221+
pub fn almost_finish(&mut self) {
222+
self.almost_finished = true;
223+
self.finish();
224+
}
225+
209226
/// Returns the mode of the timer.
210227
///
211228
/// # Examples
@@ -256,7 +273,7 @@ impl Timer {
256273
/// assert_eq!(timer.elapsed_secs(), 1.0);
257274
/// assert_eq!(repeating.elapsed_secs(), 0.5);
258275
/// ```
259-
pub fn tick(&mut self, delta: Duration) -> &Self {
276+
pub fn tick(&mut self, mut delta: Duration) -> &Self {
260277
if self.is_paused() {
261278
self.times_finished_this_tick = 0;
262279
if self.mode == TimerMode::Repeating {
@@ -270,6 +287,10 @@ impl Timer {
270287
return self;
271288
}
272289

290+
if self.almost_finished {
291+
delta -= Duration::from_nanos(1);
292+
self.almost_finished = false;
293+
}
273294
self.stopwatch.tick(delta);
274295
self.finished = self.elapsed() >= self.duration();
275296

@@ -628,6 +649,21 @@ mod tests {
628649
assert_eq!(t.times_finished_this_tick(), 34);
629650
}
630651

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

0 commit comments

Comments
 (0)