-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector.js
96 lines (96 loc) · 2.11 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
module.exports = class {
/**
*
* @param {Number} x
* @param {Number} y
*/
constructor(x, y) {
/**
* @type Number
*/
this.x = x || 0;
/**
* @type Number
*/
this.y = y || 0;
}
getDirection() {
return Math.atan2(this.y, this.x);
}
setDirection(angle) {
var magnitude = this.mag();
this.x = Math.cos((angle * Math.PI) / 180) * magnitude;
this.y = Math.sin((angle * Math.PI) / 180) * magnitude;
}
mag() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
setMag(magnitude) {
var direction = this.getDirection();
this.x = Math.cos(direction) * magnitude;
this.y = Math.sin(direction) * magnitude;
}
add(v2) {
this.x += v2.x;
this.y += v2.y;
}
sub(v2) {
this.x -= v2.x;
this.y -= v2.y;
}
mult(scalar) {
this.x *= scalar;
this.y *= scalar;
}
div(scalar) {
this.x /= scalar;
this.y /= scalar;
}
limit(max) {
if (this.mag > max) {
this.setMag(max);
return;
} else {
return;
}
}
normalize() {
var m = this.mag();
if (m > 0) {
this.div(m);
}
}
copy() {
return new Vector(this.x, this.y);
}
toString() {
return 'x: ' + this.x + ', y: ' + this.y;
}
toArray() {
return [this.x, this.y];
}
toObject() {
return { x: this.x, y: this.y };
}
getDistance(v2) {
return Math.sqrt(Math.pow(this.x - v2.x, 2) + Math.pow(this.y - v2.y, 2));
}
};
PVector = {
add: function (v1, v2) {
var v3 = new Vector(v1.x + v2.x, v1.y + v2.y);
return v3;
},
sub: function (v1, v2) {
var v3 = new Vector(v1.x - v2.x, v1.y - v2.y);
return v3;
},
mult: function (v2, v2) {
var v3 = new Vector(v1.x * v2.x, v1.y * v2.y);
return v3;
},
div: function (v1, v2) {
var v3 = new Vector(v1.x / v2.x, v1.y / v2.y);
return v3;
},
};