-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.js
53 lines (42 loc) · 885 Bytes
/
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
function Vector(x = 0, y = 0) {
this.x = x;
this.y = y;
}
Vector.prototype = {
toString() {
return "(" + this.x + ", " + this.y + ")";
},
add(vector) {
return new Vector(this.x + vector.x, this.y + vector.y);
},
subtract(vector) {
return this.add(vector.negate());
},
negate() {
return new Vector(-this.x, -this.y);
},
dot(vector) {
return this.x * vector.x + this.y * vector.y;
},
length() {
return Math.sqrt(this.dot(this));
},
multiply(scalar) {
return new Vector(this.x * scalar, this.y * scalar);
},
divide(scalar) {
if(scalar == 0)
return new Vector(0, 0);
else
return this.multiply(1 / scalar);
},
normalize() {
return this.divide(this.length());
},
angle() {
return Math.atan2(this.y, this.x);
},
fromAngle(angle, length = 1) {
return new Vector(Math.cos(angle) * length, Math.sin(angle) * length);
}
}