2023-10-27 02:26:13 +00:00
|
|
|
use instant::Instant;
|
2024-03-03 02:37:21 +00:00
|
|
|
use lyra_ecs::{Component, World};
|
2024-01-20 05:54:36 +00:00
|
|
|
use lyra_reflect::Reflect;
|
2023-10-27 02:26:13 +00:00
|
|
|
|
2024-01-06 21:49:36 +00:00
|
|
|
use crate::{plugin::Plugin, game::GameStages};
|
2023-10-27 02:26:13 +00:00
|
|
|
|
2024-01-20 05:54:36 +00:00
|
|
|
#[derive(Clone, Component, Default, Reflect)]
|
|
|
|
pub struct DeltaTime(f32, #[reflect(skip)] Option<Instant>);
|
2023-10-27 02:26:13 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-06 21:49:36 +00:00
|
|
|
/// 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<()> {
|
2023-10-27 02:26:13 +00:00
|
|
|
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);
|
|
|
|
|
2023-10-27 02:26:13 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct DeltaTimePlugin;
|
|
|
|
|
|
|
|
impl Plugin for DeltaTimePlugin {
|
|
|
|
fn setup(&self, game: &mut crate::game::Game) {
|
2024-02-23 21:38:38 +00:00
|
|
|
game.world_mut().add_resource(DeltaTime(0.0, None));
|
2024-01-06 21:49:36 +00:00
|
|
|
game.add_system_to_stage(GameStages::First, "delta_time", delta_time_system, &[]);
|
2023-10-27 02:26:13 +00:00
|
|
|
}
|
|
|
|
}
|