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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::time::Duration;
use super::game::Floatable;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Timer {
time : Duration,
time_left : Duration,
pub ready : bool,
}
impl Timer {
pub fn from_millis(ms : u64) -> Self {
let duration = Duration::from_millis(ms);
Self {
time : duration,
time_left : duration,
ready : false,
}
}
pub fn from_nanos(nanos : u64) -> Self {
let duration = Duration::from_nanos(nanos);
Self {
time : duration,
time_left : duration,
ready : false,
}
}
pub fn reset(&mut self) {
self.ready = false;
self.time_left = self.time;
}
pub fn set_millis_transient(&mut self, ms : u64) {
self.ready = false;
self.time_left = Duration::from_millis(ms);
}
pub fn update(&mut self, delta : Duration) {
if self.ready {
return;
}
if let Some(result) = self.time_left.checked_sub(delta) {
self.time_left = result;
} else {
self.ready = true;
}
}
}
impl Floatable for Timer {
fn f32(&self) -> f32 {
self.time_left.as_secs() as f32 + self.time_left.subsec_nanos() as f32 * 1e-9
}
}