-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.js
46 lines (35 loc) · 1.16 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
(function() {
"use strict";
function Vector(x, y) {
this.x = x;
this.y = y;
}
Vector.zero = function () {
return new Vector(0, 0);
};
Vector.prototype.add = function (other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.multiply = function (scalar) {
return new Vector(this.x * scalar, this.y * scalar);
};
Vector.prototype.divide = function (scalar) {
return this.multiply(1.0 / scalar);
};
Vector.prototype.subtract = function (other) {
return this.add(other.multiply(-1));
};
Vector.prototype.length = function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
};
Vector.prototype.normalize = function () {
var length = this.length();
if (length > 0) {
return this.divide(length);
}
// to prevent divide by zero errors. this isn't here to be accurate
// but rather to facilitate a nice simulation experience.
return new Vector(Math.random() - 0.5, Math.random() - 0.5);
};
phys.Vector = Vector;
})(window.phys = window.phys || {});