better time calculation

This commit is contained in:
Carter Anderson 2020-05-30 21:15:39 -07:00
parent d79caf76b4
commit a5df2ca62b
2 changed files with 16 additions and 21 deletions

View File

@ -12,7 +12,7 @@ use bevy_transform::{
}; };
use glam::{Mat3, Mat4, Quat, Vec2, Vec3}; use glam::{Mat3, Mat4, Quat, Vec2, Vec3};
use legion::prelude::IntoSystem; use legion::prelude::IntoSystem;
use time::{start_timer_system, stop_timer_system, Time}; use time::{timer_system, Time};
#[derive(Default)] #[derive(Default)]
pub struct CorePlugin; pub struct CorePlugin;
@ -36,7 +36,6 @@ impl AppPlugin for CorePlugin {
.register_property_type::<Mat3>() .register_property_type::<Mat3>()
.register_property_type::<Mat4>() .register_property_type::<Mat4>()
.register_property_type::<Quat>() .register_property_type::<Quat>()
.add_system_to_stage(stage::FIRST, start_timer_system.system()) .add_system_to_stage(stage::FIRST, timer_system.system());
.add_system_to_stage(stage::LAST, stop_timer_system.system());
} }
} }

View File

@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
pub struct Time { pub struct Time {
pub delta: Duration, pub delta: Duration,
pub instant: Instant, pub instant: Option<Instant>,
pub delta_seconds_f64: f64, pub delta_seconds_f64: f64,
pub delta_seconds: f32, pub delta_seconds: f32,
} }
@ -12,7 +12,7 @@ impl Default for Time {
fn default() -> Time { fn default() -> Time {
Time { Time {
delta: Duration::from_secs(0), delta: Duration::from_secs(0),
instant: Instant::now(), instant: None,
delta_seconds_f64: 0.0, delta_seconds_f64: 0.0,
delta_seconds: 0.0, delta_seconds: 0.0,
} }
@ -20,22 +20,18 @@ impl Default for Time {
} }
impl Time { impl Time {
pub fn start(&mut self) { pub fn update(&mut self) {
self.instant = Instant::now(); let now = Instant::now();
} if let Some(instant) = self.instant {
self.delta = now - instant;
pub fn stop(&mut self) { self.delta_seconds_f64 =
self.delta = Instant::now() - self.instant; self.delta.as_secs() as f64 + (self.delta.subsec_nanos() as f64 / 1.0e9);
self.delta_seconds_f64 = self.delta_seconds = self.delta_seconds_f64 as f32;
self.delta.as_secs() as f64 + (self.delta.subsec_nanos() as f64 / 1.0e9); }
self.delta_seconds = self.delta_seconds_f64 as f32; self.instant = Some(now);
} }
} }
pub fn start_timer_system(mut time: ResMut<Time>) { pub fn timer_system(mut time: ResMut<Time>) {
time.start(); time.update();
} }
pub fn stop_timer_system(mut time: ResMut<Time>) {
time.stop();
}