lyra-engine/lyra-game/src/delta_time.rs

42 lines
1.1 KiB
Rust
Raw Normal View History

use instant::Instant;
use lyra_ecs::{Component, world::World};
use crate::{plugin::Plugin, game::GameStages};
#[derive(Clone, Component)]
2023-10-29 21:54:04 +00:00
pub struct DeltaTime(f32, Option<Instant>);
impl std::ops::Deref for DeltaTime {
type Target = f32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for DeltaTime {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// A system that updates the [`DeltaTime``] resource.
///
/// The resource is updated in the [`GameStages::First`] stage.
pub fn delta_time_system(world: &mut World) -> anyhow::Result<()> {
let now = Instant::now();
2023-12-26 19:12:53 +00:00
let mut delta = world.get_resource_mut::<DeltaTime>();
2023-10-29 21:54:04 +00:00
delta.0 = delta.1.unwrap_or(now).elapsed().as_secs_f32();
delta.1 = Some(now);
Ok(())
}
pub struct DeltaTimePlugin;
impl Plugin for DeltaTimePlugin {
fn setup(&self, game: &mut crate::game::Game) {
2023-12-26 19:12:53 +00:00
game.world().add_resource(DeltaTime(0.0, None));
game.add_system_to_stage(GameStages::First, "delta_time", delta_time_system, &[]);
}
}