forked from ayberkydn/haxRL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVector.js
96 lines (79 loc) · 1.84 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;
}
add(vec) {
this.x += vec.x;
this.y += vec.y;
return this;
}
sub(vec) {
this.x -= vec.x;
this.y -= vec.y;
return this;
}
normalize() {
let norm = this.magnitude();
this.x /= norm;
this.y /= norm;
return this;
}
magnitude() {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
mult(n) {
this.x *= n;
this.y *= n;
return this;
}
div(n) {
this.x /= n;
this.y /= n;
return this;
}
inverse() {
this.x -= 1;
this.y -= 1;
return this;
}
copy() {
return Object.assign(new Vector(0, 0), this);
}
static div(vec1, n) {
return vec1.copy().div(n);
}
static mult(vec1, n) {
return vec1.copy().mult(n);
}
static add(vec1, vec2) {
return vec1.copy().add(vec2);
}
static sub(vec1, vec2) {
return vec1.copy().sub(vec2);
}
static normalize(vec) {
return vec.copy().normalize();
}
static inverse(vec1) {
return vec1.copy().inverse();
}
static dot(vec1, vec2) {
return vec1.x * vec2.x + vec1.y * vec2.y;
}
static dist(vec1, vec2) {
return Vector.sub(vec1, vec2).magnitude();
}
static get Unit() {
return {
up: new Vector(0, -1),
upleft: new Vector(-Math.SQRT1_2, -Math.SQRT1_2),
left: new Vector(-1, 0),
downleft: new Vector(-Math.SQRT1_2, Math.SQRT1_2),
down: new Vector(0, 1),
downright: new Vector(Math.SQRT1_2, Math.SQRT1_2),
right: new Vector(1, 0),
upright: new Vector(Math.SQRT1_2, -Math.SQRT1_2),
};
}
}