Skip to main content

paiagram_core/units/
speed.rs

1use super::distance::Distance;
2use super::time::Duration;
3use bevy::prelude::Reflect;
4use derive_more::{Add, AddAssign, Sub, SubAssign};
5use std::ops;
6
7/// The speed represented in m/s
8#[derive(Reflect, Debug, Clone, Copy, Add, AddAssign, Sub, SubAssign)]
9pub struct Velocity(pub f32);
10
11impl std::fmt::Display for Velocity {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        write!(f, "{:.2}m/s", self.0)
14    }
15}
16
17impl ops::Mul<f32> for Velocity {
18    type Output = Velocity;
19    fn mul(self, rhs: f32) -> Self::Output {
20        Self(self.0 * rhs)
21    }
22}
23
24impl ops::MulAssign<f32> for Velocity {
25    fn mul_assign(&mut self, rhs: f32) {
26        self.0 *= rhs
27    }
28}
29
30impl ops::Div<f32> for Velocity {
31    type Output = Self;
32    fn div(self, rhs: f32) -> Self::Output {
33        Self(self.0 / rhs)
34    }
35}
36
37impl ops::DivAssign<f32> for Velocity {
38    fn div_assign(&mut self, rhs: f32) {
39        self.0 /= rhs
40    }
41}
42
43impl ops::Mul<Duration> for Velocity {
44    type Output = Distance;
45    fn mul(self, rhs: Duration) -> Self::Output {
46        Distance((self.0 * rhs.0 as f32).round() as i32)
47    }
48}
49
50impl ops::Div<Velocity> for Distance {
51    type Output = Duration;
52    fn div(self, rhs: Velocity) -> Self::Output {
53        if rhs.0 == 0.0 {
54            return Duration(0);
55        }
56        Duration((self.0 as f32 / rhs.0).round() as i32)
57    }
58}
59
60impl ops::Div<Duration> for Distance {
61    type Output = Velocity;
62    fn div(self, rhs: Duration) -> Self::Output {
63        if rhs.0 == 0 {
64            return Velocity(0.0);
65        }
66        Velocity(self.0 as f32 / rhs.0 as f32)
67    }
68}