1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use bevy_ecs::ResMut;
use std::time::Duration;

#[cfg(target_arch = "wasm32")]
use instant::Instant;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;

/// Tracks elapsed time since the last update and since the App has started
pub struct Time {
    pub delta: Duration,
    pub instant: Option<Instant>,
    pub delta_seconds_f64: f64,
    pub delta_seconds: f32,
    pub seconds_since_startup: f64,
    pub startup: Instant,
}

impl Default for Time {
    fn default() -> Time {
        Time {
            delta: Duration::from_secs(0),
            instant: None,
            startup: Instant::now(),
            delta_seconds_f64: 0.0,
            seconds_since_startup: 0.0,
            delta_seconds: 0.0,
        }
    }
}

impl Time {
    pub fn update(&mut self) {
        let now = Instant::now();
        if let Some(instant) = self.instant {
            self.delta = now - instant;
            self.delta_seconds_f64 = self.delta.as_secs_f64();
            self.delta_seconds = self.delta.as_secs_f32();
        }

        let duration_since_startup = now - self.startup;
        self.seconds_since_startup = duration_since_startup.as_secs_f64();
        self.instant = Some(now);
    }

    pub fn time_since_startup(&self) -> Duration {
        Instant::now() - self.startup
    }
}

pub(crate) fn time_system(mut time: ResMut<Time>) {
    time.update();
}