-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.js
96 lines (76 loc) · 1.56 KB
/
vector.js
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
94
95
96
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
get() {
return new Vector(this.x, this.y);
}
set(x, y) {
this.x = x;
this.y = y;
}
add(v) {
this.x += v.x;
this.y += v.y;
}
static add(v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
}
sub(v) {
this.x -= v.x;
this.y -= v.y;
}
static sub(v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
}
mult(n) {
this.x = this.x * n;
this.y = this.y * n;
}
static mult(v1, v2) {
return new Vector(v1.x * v2.x, v1.y * v2.y);
}
static multN(v1, n) {
return new Vector(v1.x * n, v1.y * n);
}
div(n) {
this.x = this.x / n;
this.y = this.y / n;
}
static div(v1, v2) {
return new Vector(v1.x / v2.x, v1.y / v2.y);
}
static divN(v1, n) {
return new Vector(v1.x / n, v1.y / n);
}
mag() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
magSq() {
return this.x * this.x + this.y * this.y;
}
normalize() {
var m = this.mag();
if (m !== 0 && m !== 1) {
this.div(m);
}
}
limit(max) {
if (this.magSq() > max * max) {
this.normalize();
this.mult(max);
}
}
heading() {
var angle = Math.atan2(-this.y, this.x);
return -1 * angle;
}
static random2D() {
return Vector.fromAngle(Math.random() * Math.TAU);
}
static fromAngle(angle) {
return new Vector(Math.cos(angle), Math.sin(angle));
}
}
export default Vector;