Repository navigation
Expand file tree
/
Copy path_Vector.js
More file actions
111 lines (89 loc) · 1.6 KB
/
Copy path_Vector.js
File metadata and controls
111 lines (89 loc) · 1.6 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
(function(global){ 'use strict';
var Vector = function(x, y){
this.x = x || 0;
this.y = y || 0;
};
Vector.prototype = {
clone: function(){
return new Vector(this.x, this.y);
},
add: function(vec){
this.x += vec.x;
this.y += vec.y;
return this;
},
sub: function(vec){
this.x -= vec.x;
this.y -= vec.y;
return this;
},
subVal: function(val){
this.x -= val;
this.y -= val;
return this;
},
mult: function(mul){
this.x *= mul;
this.y *= mul;
return this;
},
div: function(div){
if (div === 0) {
return this;
}
this.x /= div;
this.y /= div;
return this;
},
mag: function(){
return Math.sqrt(
this.x * this.x +
this.y * this.y
);
},
limit: function(max){
if (this.mag() > max) {
this.normalize();
this.mult(max);
}
return this;
},
normalize: function(){
var mag = this.mag();
if (mag === 0) {
return this;
}
this.div(mag);
return this;
},
heading: function(){
return Math.atan2(this.y, this.x);
},
set: function(vec){
this.x = vec.x;
this.y = vec.y;
return this;
}
};
Vector.add = function(vec1, vec2){
return vec1.clone().add(vec2.clone());
};
Vector.sub = function(vec1, vec2){
return vec1.clone().sub(vec2.clone());
};
Vector.mult = function(vec, mult){
return vec.clone().mult(mult);
};
Vector.div = function(vec, div){
return vec.clone().div(div);
};
// Ripped from processing
Vector.random2D = function(){
var angle = Math.random(0, 1) * Math.PI * 2;
return new Vector(Math.cos(angle), Math.sin(angle));
};
Vector.coerce = function(obj){
return new Vector(obj.x, obj.y);
};
global.Vector = Vector;
})(this);