#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec2 {
pub x: f32,
pub y: f32,
}
impl Vec2 {
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
pub fn zero() -> Self {
Self::new(0.0, 0.0)
}
pub fn one() -> Self {
Self::new(1.0, 1.0)
}
pub fn up() -> Self {
Self::new(0.0, 1.0)
}
pub fn right() -> Self {
Self::new(1.0, 0.0)
}
pub fn magnitude(&self) -> f32 {
(self.x * self.x + self.y * self.y).sqrt()
}
pub fn magnitude_squared(&self) -> f32 {
self.x * self.x + self.y * self.y
}
pub fn normalized(&self) -> Self {
let mag = self.magnitude();
if mag > 0.0 {
Self::new(self.x / mag, self.y / mag)
} else {
Self::zero()
}
}
pub fn distance(&self, other: Vec2) -> f32 {
(*self - other).magnitude()
}
pub fn dot(&self, other: Vec2) -> f32 {
self.x * other.x + self.y * other.y
}
}
impl std::ops::Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 {
Vec2::new(self.x + other.x, self.y + other.y)
}
}
impl std::ops::Sub for Vec2 {
type Output = Vec2;
fn sub(self, other: Vec2) -> Vec2 {
Vec2::new(self.x - other.x, self.y - other.y)
}
}
impl std::ops::Mul<f32> for Vec2 {
type Output = Vec2;
fn mul(self, scalar: f32) -> Vec2 {
Vec2::new(self.x * scalar, self.y * scalar)
}
}
impl std::ops::Div<f32> for Vec2 {
type Output = Vec2;
fn div(self, scalar: f32) -> Vec2 {
Vec2::new(self.x / scalar, self.y / scalar)
}
}