From 9b3f6f0595083bceca1164348dbfedb119e4b603 Mon Sep 17 00:00:00 2001 From: Bob van der Linden Date: Sat, 28 Dec 2024 22:17:41 +0100 Subject: [PATCH] add Angle struct This is to represent Angle and translate between radians, degrees and Vec2D. --- src/math.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/math.rs b/src/math.rs index f41a6b1..799a162 100644 --- a/src/math.rs +++ b/src/math.rs @@ -10,6 +10,38 @@ pub struct Vec2D { pub y: f32, } +#[derive(Default, Debug, Copy, Clone, PartialEq)] +pub struct Angle { + pub radians: f32, +} +impl Angle { + pub fn from_radians(radians: f32) -> Self { + Self { radians } + } + + pub fn from_degrees(degrees: f32) -> Self { + Self { + radians: degrees * PI / 180.0, + } + } + + pub fn cos(&self) -> f32 { + self.radians.cos() + } + + pub fn sin(&self) -> f32 { + self.radians.sin() + } +} + +impl Mul for Angle { + type Output = Angle; + + fn mul(self, rhs: f32) -> Self::Output { + Angle::from_radians(self.radians * rhs) + } +} + impl Vec2D { pub fn zero() -> Self { Self { x: 0.0, y: 0.0 } @@ -27,6 +59,24 @@ impl Vec2D { self.x * self.x + self.y * self.y } + /** + * Get the angle of the vector. + * Angle of 0 is the positive x-axis. + * Angle of PI/2 is the positive y-axis. + */ + pub fn angle(&self) -> Angle { + Angle::from_radians(self.y.atan2(self.x)) + } + + /** + * Create a vector from an angle. + * Angle of 0 is the positive x-axis. + * Angle of PI/2 is the positive y-axis. + */ + pub fn from_angle(angle: Angle) -> Vec2D { + Vec2D::new(angle.cos(), angle.sin()) + } + pub fn snapped_vector_15deg(&self) -> Vec2D { let current_angle = (self.y / self.x).atan(); let current_norm2 = self.norm2();