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
|
use std::ops::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec2d {
pub x: f64,
pub y: f64
}
impl Vec2d {
pub fn new(x: f64, y: f64) -> Vec2d {
Vec2d {x, y}
}
pub fn distance(&self, other: Vec2d) -> f64 {
self.distance_squared(other).sqrt()
}
pub fn distance_squared(&self, other: Vec2d) -> f64 {
((other.x-self.x).powi(2) + (other.y-self.y).powi(2))
}
pub fn magnitude(&self) -> f64 {
self.magnitude_squared().sqrt()
}
pub fn magnitude_squared(&self) -> f64 {
self.x.powi(2) + self.y.powi(2)
}
pub fn angle(&self) -> f64 {
self.y.atan2(self.x)
}
pub fn unit(&self) -> Vec2d {
let mag = self.magnitude();
Vec2d {
x: self.x / mag,
y: self.y / mag
}
}
}
impl Add for Vec2d {
type Output = Vec2d;
fn add(self, other: Self) -> Self {
Vec2d {
x: self.x + other.x,
y: self.y + other.y
}
}
}
impl Sub for Vec2d {
type Output = Vec2d;
fn sub(self, other: Self) -> Self {
Vec2d {
x: self.x - other.x,
y: self.y - other.y
}
}
}
impl Neg for Vec2d {
type Output = Vec2d;
fn neg(self) -> Self {
Vec2d {
x: -self.x,
y: -self.y
}
}
}
impl Mul<f64> for Vec2d {
type Output = Vec2d;
fn mul(self, rhs: f64) -> Self {
Vec2d {
x: self.x * rhs,
y: self.y * rhs
}
}
}
|