oort_api/
vec.rs

1/// A two-dimensional vector.
2pub type Vec2 = maths_rs::vec::Vec2<f64>;
3
4/// Returns a [Vec2] with the given coordinates.
5pub fn vec2(x: f64, y: f64) -> Vec2 {
6    Vec2::new(x, y)
7}
8
9/// Extra methods for Vec2.
10pub trait Vec2Extras {
11    /// Returns the length (or distance from origin).
12    fn length(self) -> f64;
13
14    /// Returns a normalized vector with the same direction but length of 1.
15    fn normalize(self) -> Vec2;
16
17    /// Returns the distance to `other`.
18    fn distance(self, other: Vec2) -> f64;
19
20    /// Returns the dot product with `other`.
21    fn dot(self, other: Vec2) -> f64;
22
23    /// Returns the angle of the vector (in radians).
24    fn angle(self) -> f64;
25
26    /// Returns this vector rotated by the given angle (in radians).
27    fn rotate(self, angle: f64) -> Vec2;
28}
29
30impl Vec2Extras for Vec2 {
31    fn length(self) -> f64 {
32        (self.x * self.x + self.y * self.y).sqrt()
33    }
34
35    fn normalize(self) -> Vec2 {
36        self / self.length()
37    }
38
39    fn distance(self, other: Vec2) -> f64 {
40        (self - other).length()
41    }
42
43    fn dot(self, other: Vec2) -> f64 {
44        self.x * other.x + self.y * other.y
45    }
46
47    fn angle(self) -> f64 {
48        let mut a = self.y.atan2(self.x);
49        if a < 0.0 {
50            a += std::f64::consts::TAU;
51        }
52        a
53    }
54
55    fn rotate(self, angle: f64) -> Vec2 {
56        let cos = angle.cos();
57        let sin = angle.sin();
58        Vec2 {
59            x: self.x * cos - self.y * sin,
60            y: self.x * sin + self.y * cos,
61        }
62    }
63}