From 4fb356822ef98241d2e44b0b0bd31d7f214f9f20 Mon Sep 17 00:00:00 2001 From: lamp Date: Sun, 5 Mar 2023 21:27:40 +0000 Subject: init --- src/vec2.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/vec2.rs (limited to 'src/vec2.rs') diff --git a/src/vec2.rs b/src/vec2.rs new file mode 100644 index 0000000..077433a --- /dev/null +++ b/src/vec2.rs @@ -0,0 +1,52 @@ +use auto_ops::{impl_op_ex, impl_op_ex_commutative}; + +#[derive(Clone)] +pub struct Vec2 { + pub x: T, + pub y: T, +} + +impl Vec2 { + pub fn new() -> Vec2 { + Vec2 { x: 0.0, y: 0.0 } + } + + pub fn rotate(&mut self, radians: f64) { + *self = Vec2 { + x: self.x * radians.cos() - self.y * radians.sin(), + y: self.x * radians.sin() + self.y * radians.cos(), + }; + } + + pub fn length_squared(&self) -> f64 { + self.x * self.x + self.y * self.y + } + + pub fn length(&self) -> f64 { + self.length_squared().sqrt() + } + + pub fn as_usize(&self) -> Vec2 { + Vec2 { + x: self.x as usize, + y: self.y as usize, + } + } +} + +impl_op_ex!(+ |lhs: &Vec2, rhs: &Vec2| -> Vec2 { Vec2 { x: lhs.x + rhs.x, y: lhs.y + rhs.y } }); +impl_op_ex!(-|lhs: &Vec2, rhs: &Vec2| -> Vec2 { + Vec2 { + x: lhs.x - rhs.x, + y: lhs.y - rhs.y, + } +}); +impl_op_ex!(+= |lhs: &mut Vec2, rhs: &Vec2| { *lhs = Vec2 { x: lhs.x + rhs.x, y: lhs.y + rhs.y } }); +impl_op_ex!(-= |lhs: &mut Vec2, rhs: &Vec2| { *lhs = Vec2 { x: lhs.x - rhs.x, y: lhs.y - rhs.y } }); +impl_op_ex_commutative!(*|lhs: &Vec2, rhs: &f64| -> Vec2 { + Vec2 { + x: lhs.x * rhs, + y: lhs.y * rhs, + } +}); +impl_op_ex!(/ |lhs: &Vec2, rhs: &f64| -> Vec2 { lhs * (1.0 / rhs) }); -- cgit v1.2.3