-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvector.js
98 lines (98 loc) · 2.61 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
97
98
(function() {
var Vector;
Vector = (function() {
Vector.prototype.x = 0;
Vector.prototype.y = 0;
Vector.prototype.z = 0;
function Vector(x, y, z) {
this.set(x, y, z);
}
Vector.prototype.add = function(v) {
this.x += v.x;
this.y += v.y;
return this.z += v.z;
};
Vector.prototype.get = function() {
return new Vector(this.x, this.y, this.z);
};
Vector.prototype.cross = function(v) {
return new Vector(this.y * v.z - v.y * this.z, this.z * v.x - v.z * this.x, this.x * v.y - v.x * this.y);
};
Vector.prototype.div = function(v) {
if (typeof v === 'number') {
v = new Vector(v, v, v);
}
this.x /= v.x;
this.y /= v.y;
return this.z /= v.z;
};
Vector.prototype.dist = function(v) {
var dx, dy, dz;
if (typeof v === 'number') {
v = new Vector(v, v, v);
}
dx = v.x - this.x;
dy = v.y - this.y;
dz = v.z - this.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
};
Vector.prototype.dot = function(v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
};
Vector.prototype.heading2D = function() {
return -Math.atan2(-this.y, this.x);
};
Vector.prototype.limit = function(high) {
if (this.mag() > high) {
this.normalize();
return this.mult(high);
}
};
Vector.prototype.mag = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
Vector.prototype.mult = function(v) {
this.x *= v.x;
this.y *= v.y;
return this.z *= v.z;
};
Vector.prototype.normalize = function() {
var m;
m = this.mag();
if (m > 0) {
return this.div(m);
}
};
Vector.prototype.set = function(x, y, z) {
var _ref;
return _ref = [x, y, z], this.x = _ref[0], this.y = _ref[1], this.z = _ref[2], _ref;
};
Vector.prototype.sub = function(v) {
this.x -= v.z;
this.y -= v.y;
return this.z -= v.z;
};
Vector.prototype.toArray = function() {
return [this.x, this.y, this.z];
};
Vector.prototype.toString = function() {
return "x:@x, y:@y, z:@z";
};
return Vector;
})();
Vector.dist = function(v1, v2) {
return v1.dist(v2);
};
Vector.dot = function(v1, v2) {
return v1.dot(v2);
};
Vector.cross = function(v1, v2) {
return v1.cross(v2);
};
Vector.angleBetween = function(v1, v2) {
return Math.acos(v1.dot(v2) / (v1.mag() * v2.mag()));
};
if (typeof exports !== "undefined" && exports !== null) {
exports.Vector = Vector;
}
}).call(this);