-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathvector.js
83 lines (66 loc) · 1.47 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
var vector = {
_x: 1,
_y: 0,
create: function(x, y) {
var obj = Object.create(this);
obj.setX(x);
obj.setY(y);
return obj;
},
setX: function(value) {
this._x = value;
},
getX: function() {
return this._x;
},
setY: function(value) {
this._y = value;
},
getY: function() {
return this._y;
},
setAngle: function(angle) {
var length = this.getLength();
this._x = Math.cos(angle) * length;
this._y = Math.sin(angle) * length;
},
getAngle: function() {
return Math.atan2(this._y, this._x);
},
setLength: function(length) {
var angle = this.getAngle();
this._x = Math.cos(angle) * length;
this._y = Math.sin(angle) * length;
},
getLength: function() {
return Math.sqrt(this._x * this._x + this._y * this._y);
},
add: function(v2) {
return vector.create(this._x + v2.getX(), this._y + v2.getY());
},
subtract: function(v2) {
return vector.create(this._x - v2.getX(), this._y - v2.getY());
},
multiply: function(val) {
return vector.create(this._x * val, this._y * val);
},
divide: function(val) {
return vector.create(this._x / val, this._y / val);
},
addTo: function(v2) {
this._x += v2.getX();
this._y += v2.getY();
},
subtractFrom: function(v2) {
this._x -= v2.getX();
this._y -= v2.getY();
},
multiplyBy: function(val) {
this._x *= val;
this._y *= val;
},
divideBy: function(val) {
this._x /= val;
this._y /= val;
}
};