wasm4fun_time/
timer.rs

1// Copyright Claudio Mattera 2022.
2//
3// Distributed under the MIT License or the Apache 2.0 License at your option.
4// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
5// online at
6// https://opensource.org/licenses/MIT
7// https://opensource.org/licenses/Apache-2.0
8
9use super::Ticker;
10
11/// A timer to keep track of elapsed time
12#[derive(Clone)]
13pub struct Timer(u32);
14
15impl Timer {
16    /// Create a new timer
17    pub fn new() -> Self {
18        Self(0)
19    }
20
21    /// Update the timer
22    ///
23    /// This function must be called at each frame.
24    pub fn update(&mut self) {
25        if Ticker.within_second() == 0 {
26            self.0 += 1;
27        }
28    }
29
30    /// Return the time since the timer started in seconds
31    pub fn get(&self) -> u32 {
32        self.0
33    }
34}
35
36impl Default for Timer {
37    fn default() -> Self {
38        Self::new()
39    }
40}