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
//! Frame timing, published into the ECS world and readable from scenes.
use std::time::Instant;
use crate::ecs::Resource;
/// Seconds elapsed since the last frame and since the app started.
///
/// Updated once per frame by [`crate::AppState::tick_time`].
#[derive(Resource, Clone, Copy, Debug, Default)]
pub struct Time {
pub delta: f32,
pub elapsed: f32,
}
/// Drives [`Time`] from the wall clock.
pub struct Clock {
started: Instant,
last_frame: Instant,
}
impl Clock {
pub fn new() -> Self {
let now = Instant::now();
Self {
started: now,
last_frame: now,
}
}
/// Advances the clock and returns the new [`Time`].
pub fn tick(&mut self) -> Time {
let now = Instant::now();
let delta = now.duration_since(self.last_frame).as_secs_f32();
self.last_frame = now;
Time {
delta,
elapsed: now.duration_since(self.started).as_secs_f32(),
}
}
}
impl Default for Clock {
fn default() -> Self {
Self::new()
}
}