diff options
author | HampusM <hampus@hampusmat.com> | 2023-10-24 21:44:56 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2023-10-24 21:44:56 +0200 |
commit | 3d0de3f951ec2da7a2d41c6958d0d3583a7832a0 (patch) | |
tree | 1e1e06606bafb51bd4b1014b2086319f7f50ca3d /engine | |
parent | c846fe5e269a827b3c324fb66b75be3fabc56a57 (diff) |
feat(engine): add delta time
Diffstat (limited to 'engine')
-rw-r--r-- | engine/src/lib.rs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/engine/src/lib.rs b/engine/src/lib.rs index ce953f8..bec1e30 100644 --- a/engine/src/lib.rs +++ b/engine/src/lib.rs @@ -1,6 +1,7 @@ #![deny(clippy::all, clippy::pedantic)] use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use glfw::{Window, WindowBuilder}; @@ -29,6 +30,7 @@ pub struct Engine objects: BTreeMap<ObjectId, Object>, window: Window, camera: Camera, + delta_time: Duration, } impl Engine @@ -63,6 +65,7 @@ impl Engine window, objects: BTreeMap::new(), camera: Camera::new(), + delta_time: Duration::ZERO, }) } @@ -95,7 +98,11 @@ impl Engine /// Will return `Err` if updating the window fails. pub fn start(&mut self, mut func: impl FnMut(&mut Self)) -> Result<(), Error> { + let mut prev_frame_start: Option<Instant> = None; + while !self.window.should_close() { + self.update_delta_time(&mut prev_frame_start); + func(self); let window_size = self.window.size().map_err(Error::GetWindowSizeFailed)?; @@ -118,6 +125,25 @@ impl Engine { &mut self.camera } + + /// Returns the current delta time. Will be 0 if not called from the function + /// passed to [`start`]. + #[must_use] + pub fn delta_time(&self) -> &Duration + { + &self.delta_time + } + + fn update_delta_time(&mut self, prev_frame_start: &mut Option<Instant>) + { + let frame_start_time = Instant::now(); + + if let Some(last_frame_start) = prev_frame_start { + self.delta_time = frame_start_time.duration_since(*last_frame_start); + } + + *prev_frame_start = Some(frame_start_time); + } } /// Engine Error |