-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathVector.js
82 lines (77 loc) · 2.13 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
define(['vendor/lodash'],function(){
"use strict";
function Vector(x,y) {
this.x = x || 0;
this.y = y || 0;
}
_.extend(Vector.prototype, {
getMagnitude : function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
multiply : function( scaleFactor ){
this.x *= scaleFactor;
this.y *= scaleFactor;
},
add : function( vector ){
this.x += vector.x;
this.y += vector.y;
},
vectorTo : function (vector) {
return new Vector(vector.x - this.x, vector.y - this.y);
},
withinBounds : function(point, size) {
var radius = ~~(size/2) + 1;
return this.x >= point.x - radius &&
this.x <= point.x + radius &&
this.y >= point.y - radius &&
this.y <= point.y + radius ;
},
getAngle : function() {
var ratio = 0;
var offset = 0;
if (this.x > 0) {
if (this.y > 0) {
offset = 0;
ratio = this.y / this.x;
} else {
offset = (3 * Math.PI)/2;
ratio = this.x / this.y;
}
} else {
if (this.y > 0) {
offset = Math.PI / 2;
ratio = this.x / this.y;
} else {
offset = Math.PI;
ratio = this.y / this.x;
}
}
var angle = Math.atan(Math.abs(ratio)) + offset;
return angle;
},
getAngleDegrees : function() {
return this.getAngle() * 180 / Math.PI;
},
jitter : function(jitterAmount) {
return new Vector(
this.x + this.x * jitterAmount * Math.random(),
this.y + this.y * jitterAmount * Math.random()
);
},
copy : function() {
return new Vector(this.x,this.y);
},
toString : function() {
return this.x.toFixed(3).replace(/\.?0+$/,'') +","+ this.y.toFixed(3).replace(/\.?0+$/,'');
}
});
Vector.fromAngle = function (angle, magnitude) {
return new Vector(magnitude * Math.cos(angle), magnitude * Math.sin(angle));
};
// x,y
Vector.fromString = function (string) {
var parts = string.split(',');
return new Vector(parseFloat(parts[0]),parseFloat(parts[1]));
};
return Vector;
});