Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::ops::Add;
- use std::ops::Sub;
- use std::ops::Mul;
- use std::ops::Div;
- use std::ops::AddAssign;
- use std::ops::SubAssign;
- use std::ops::MulAssign;
- use std::ops::DivAssign;
- use rand::prelude::*;
- #[derive(Copy, Clone)]
- pub struct Vector2D {
- pub x: f32,
- pub y: f32,
- }
- impl Default for Vector2D {
- fn default() -> Self {
- let mut rng = thread_rng();
- Self {
- x: 0.0,
- y: 0.0,
- }
- }
- }
- impl Vector2D {
- pub fn new(x: f32, y: f32) -> Self {
- Self {
- x,
- y,
- }
- }
- pub fn random() -> Self {
- let mut rng = thread_rng();
- Self {
- x: rng.gen_range(0.0, crate::WIDTH),
- y: rng.gen_range(0.0, crate::HEIGHT),
- }
- }
- pub fn random_unit() -> Self {
- let mut rng = thread_rng();
- let angle = rng.gen_range(0.0, std::f32::consts::TAU);
- Self::up().rotate(angle)
- }
- pub fn zero() -> Self { Self { x: 0.0, y: 0.0 }}
- pub fn up() -> Self { Self { x: 0.0, y: -1.0 }}
- pub fn down() -> Self { Self { x: 0.0, y: 1.0 }}
- pub fn left() -> Self { Self { x: -1.0, y: 0.0 }}
- pub fn right() -> Self { Self { x: 1.0, y: 0.0 }}
- pub fn rotate(&self, angle: f32) -> Self {
- Self {
- x: (angle.cos() * self.x) - (angle.sin() * self.y),
- y: (angle.sin() * self.x) + (angle.cos() * self.y),
- }
- }
- pub fn to_array(&self) -> [f32; 2] {
- [self.x, self.y]
- }
- pub fn normalise(&self) -> Self {
- let length = self.length();
- if length == 0.0 {
- Self::zero()
- } else {
- Self {
- x: self.x / length,
- y: self.y / length,
- }
- }
- }
- pub fn distance(self, other: Self) -> f32 {
- (self - other).length()
- }
- pub fn length(&self) -> f32 {
- (self.x.powi(2) + self.y.powi(2)).sqrt()
- }
- }
- impl Add for Vector2D {
- type Output = Self;
- fn add(self, other: Self) -> Self {
- Self {
- x: self.x + other.x,
- y: self.y + other.y,
- }
- }
- }
- impl Sub for Vector2D {
- type Output = Self;
- fn sub(self, other: Self) -> Self {
- Self {
- x: self.x - other.x,
- y: self.y - other.y,
- }
- }
- }
- impl Mul<f32> for Vector2D {
- type Output = Self;
- fn mul(self, n: f32) -> Self {
- Self {
- x: self.x * n,
- y: self.y * n,
- }
- }
- }
- impl Div<f32> for Vector2D {
- type Output = Self;
- fn div(self, n: f32) -> Self {
- Self {
- x: self.x / n,
- y: self.y / n,
- }
- }
- }
- impl AddAssign for Vector2D {
- fn add_assign(&mut self, other: Self) {
- self.x += other.x;
- self.y += other.y;
- }
- }
- impl SubAssign for Vector2D {
- fn sub_assign(&mut self, other: Self) {
- self.x -= other.x;
- self.y -= other.y;
- }
- }
- impl MulAssign<f32> for Vector2D {
- fn mul_assign(&mut self, n: f32) {
- self.x *= n;
- self.y *= n;
- }
- }
- impl DivAssign<f32> for Vector2D {
- fn div_assign(&mut self, n: f32) {
- self.x /= n;
- self.y /= n;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement