use crate::conversion::Conversion;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Vector2 {
v: [f32; 2]
}
impl Vector2 {
pub fn new(x: f32, y: f32) -> Vector2 {
Self {
v: [
x, y
]
}
}
pub fn get_vector(&self) -> [f32; 2] {
self.v
}
pub fn get_vector_mut(&mut self) -> &mut [f32; 2] {
&mut self.v
}
pub fn x(&self) -> f32 {
self.v[0]
}
pub fn y(&self) -> f32 {
self.v[1]
}
pub fn length(&self) -> f32 {
(self.x() * self.x() + self.y() * self.y()).sqrt()
}
pub fn dot(&self, v: &Vector2) -> f32 {
self.x() * v.x() + self.y() * v.y()
}
pub fn cross(&self, v: &Vector2) -> f32 {
self.x() * v.y() - self.y() * v.x()
}
pub fn normalize(&self) -> Vector2 {
if self.length() <= 0.0 {
return 0.0.convert()
}
return Vector2::new(
self.x() / self.length(),
self.y() / self.length()
)
}
}
impl std::ops::Add for Vector2 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
v: [
self.x() + rhs.x(),
self.y() + rhs.y(),
]
}
}
}
impl std::ops::AddAssign for Vector2 {
fn add_assign(&mut self, rhs: Self) {
*self = Self {
v: [
self.x() + rhs.x(),
self.y() + rhs.y(),
]
}
}
}
impl std::ops::Sub for Vector2 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self {
v: [
self.x() - rhs.x(),
self.y() - rhs.y(),
]
}
}
}
impl std::ops::SubAssign for Vector2 {
fn sub_assign(&mut self, rhs: Self) {
*self = Self {
v: [
self.x() - rhs.x(),
self.y() - rhs.y(),
]
}
}
}
impl std::ops::Mul for Vector2 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self {
v: [
self.x() * rhs.x(),
self.y() * rhs.y(),
]
}
}
}
impl std::ops::MulAssign for Vector2 {
fn mul_assign(&mut self, rhs: Self) {
*self = Self {
v: [
self.x() * rhs.x(),
self.y() * rhs.y(),
]
}
}
}
impl std::ops::Div for Vector2 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Self {
v: [
self.x() / rhs.x(),
self.y() / rhs.y(),
]
}
}
}
impl std::ops::DivAssign for Vector2 {
fn div_assign(&mut self, rhs: Self) {
*self = Self {
v: [
self.x() / rhs.x(),
self.y() / rhs.y(),
]
}
}
}