Skip to main content

some_math_lib/util/vector/
vector2.rs

1
2use std::ops::{Add, Sub, Mul, Div};
3use super::vector3::Vector3;
4
5/// A 2-dimensional vector.
6#[derive(Debug, Copy, Clone)]
7pub struct Vector2 {
8    pub x: f64,
9    pub y: f64,
10}
11
12impl Vector2 {
13    /// Creates a new vector with components ```x``` and ```y```.
14    pub fn new(x: f64, y: f64) -> Self {
15        Vector2 { x, y }
16    }
17
18    /// Returns the squared magnitude of the vector.
19    pub fn squared_magnitude(&self) -> f64 {
20        self.x.powi(2) + self.y.powi(2)
21    }
22
23    /// Returns the magnitude of the vector.
24    pub fn magnitude(&self) -> f64 {
25        self.squared_magnitude().sqrt()
26    }
27
28    /// Returns the dot product of ```self``` and ```rhs```.
29    pub fn dot_product(&self, rhs: &Self) -> f64 {
30        (self.x * rhs.x) + (self.y * rhs.y)
31    }
32
33    /// Returns the magnitude of the vector formed by the cross product of 
34    /// ```self``` and ```rhs```.
35    pub fn cross_product_magnitude(&self, &rhs: &Self) -> f64 {
36        (self.x * rhs.y) - (self.y * rhs.x)
37    }
38
39    /// Returns a ```Vector3``` with an ```x``` and ```y``` of 
40    /// ```0.0``` and a ```z``` of the computed magnitude.
41    pub fn cross_product(&self, rhs: &Self) -> Vector3 {
42        Vector3 {
43            x: 0.0, y: 0.0,
44            z: self.cross_product_magnitude(rhs)
45        }
46    }
47}
48
49impl Add for Vector2 {
50    type Output = Self;
51
52    fn add(self, rhs: Self) -> Self::Output {
53        Vector2 {
54            x: self.x + rhs.x,
55            y: self.y + rhs.y,
56        }
57    }
58}
59impl Sub for Vector2 {
60    type Output = Self;
61
62    fn sub(self, rhs: Self) -> Self::Output {
63        Vector2 {
64            x: self.x - rhs.x,
65            y: self.y - rhs.y,
66        }
67    }
68}
69impl Mul<f64> for Vector2 {
70    type Output = Self;
71
72    fn mul(self, scalar: f64) -> Self::Output {
73        Vector2 {
74            x: self.x * scalar,
75            y: self.y * scalar,
76        }
77    }
78}
79impl Div<f64> for Vector2 {
80    type Output = Self;
81
82    fn div(self, scalar: f64) -> Self::Output {
83        Vector2 {
84            x: self.x / scalar,
85            y: self.y / scalar,
86        }
87    }
88}