1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use crate::vector::Dist;
use std::ops::{Add, AddAssign, Div, Mul, Sub};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vector2D {
pub x: f64,
pub y: f64,
}
impl Vector2D {
pub const ZERO: Vector2D = Vector2D { x: 0.0, y: 0.0 };
pub fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
pub fn dist_squared(self) -> f64 {
self.x * self.x + self.y * self.y
}
pub fn normalize(self) -> Self {
self / self.dist()
}
}
impl Dist for Vector2D {
fn dist(&self) -> f64 {
self.dist_squared().sqrt()
}
}
impl Mul<f64> for Vector2D {
type Output = Self;
fn mul(self, rhs: f64) -> Self {
Self {
x: self.x * rhs,
y: self.y * rhs,
}
}
}
impl Mul<Vector2D> for f64 {
type Output = Vector2D;
fn mul(self, rhs: Vector2D) -> Vector2D {
Vector2D {
x: self * rhs.x,
y: self * rhs.y,
}
}
}
impl Div<f64> for Vector2D {
type Output = Self;
fn div(self, rhs: f64) -> Self {
Self {
x: self.x / rhs,
y: self.y / rhs,
}
}
}
impl Sub for Vector2D {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
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 AddAssign for Vector2D {
fn add_assign(&mut self, other: Self) {
self.x += other.x;
self.y += other.y;
}
}