Last active
October 17, 2018 17:30
-
-
Save ElectricCoffee/0243fa842a2d924e4213a24c7552f7f3 to your computer and use it in GitHub Desktop.
Vector2D struct in the style of Unity's Vector2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::f32; | |
#[derive(Debug, Clone, PartialEq, PartialOrd)] | |
pub struct Vector2D { | |
pub x: f32, | |
pub y: f32, | |
} | |
impl Default for Vector2D { | |
fn default() -> Self { | |
Vector2D { x: 0.0, y: 0.0 } | |
} | |
} | |
impl From<(f32, f32)> for Vector2D { | |
fn from(input: (f32, f32)) -> Vector2D { | |
Vector2D { | |
x: input.0, | |
y: input.1, | |
} | |
} | |
} | |
impl Vector2D { | |
pub fn up() -> Vector2D { | |
Vector2D { x: 0.0, y: 1.0 } | |
} | |
pub fn down() -> Vector2D { | |
Vector2D { x: 0.0, y: -1.0 } | |
} | |
pub fn left() -> Vector2D { | |
Vector2D { x: -1.0, y: 0.0 } | |
} | |
pub fn right() -> Vector2D { | |
Vector2D { x: 1.0, y: 0.0 } | |
} | |
pub fn negative_infinity() -> Vector2D { | |
Vector2D { x: f32::NEG_INFINITY, y: f32::NEG_INFINITY } | |
} | |
pub fn positive_infinity() -> Vector2D { | |
Vector2D { x: f32::INFINITY, y: f32::INFINITY } | |
} | |
pub fn magnitude(&self) -> f32 { | |
(self.x.powi(2) + self.y.powi(2)).sqrt() | |
} | |
pub fn normalized(&self) -> Vector2D { | |
let mag = self.magnitude(); | |
Vector2D { x: self.x / mag, y: self.y / mag } | |
} | |
pub fn normalize(&mut self) { | |
*self = self.normalized(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment