summaryrefslogtreecommitdiff
path: root/engine/src/delta_time.rs
blob: a26007d932b78dd0345fd2d13b5d8792533b0025 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::time::{Duration, Instant};

use crate::ecs::component::local::Local;
use crate::ecs::sole::Single;
use crate::ecs::{Component, Sole};

#[derive(Debug, Clone, Default, Sole)]
pub struct DeltaTime
{
    pub duration: Duration,
}

#[derive(Debug, Clone, Default, Component)]
pub struct LastUpdate
{
    pub time: Option<Instant>,
}

/// Updates the current delta time.
///
/// # Panics
/// Will panic if no delta time component exists.
pub fn update(mut delta_time: Single<DeltaTime>, mut last_update: Local<LastUpdate>)
{
    let Ok(delta_time) = delta_time.get_mut() else {
        unreachable!();
    };

    let current_time = Instant::now();

    if let Some(last_update_time) = last_update.time {
        delta_time.duration = current_time.duration_since(last_update_time);
    }

    last_update.time = Some(current_time);
}