-
Notifications
You must be signed in to change notification settings - Fork 1
/
vector.js
78 lines (64 loc) · 2 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
var Vector = (function () {
"use strict";
var Vector = function (x, y) {
this.x = Math.floor(x || 0);
this.y = Math.floor(y || 0);
};
// add two vectors together and return a new one
Vector.prototype.add = function (v2) {
return new Vector(this.x + v2.x, this.y + v2.y);
};
// add a vector to this one
Vector.prototype.addTo = function (v2) {
this.x += v2.x;
this.y += v2.y;
return this;
};
// subtract two vectors and reutn a new one
Vector.prototype.subtract = function (v2) {
return new Vector(this.x - v2.x, this.y - v2.y);
};
// subtract a vector from this one
Vector.prototype.subtractFrom = function (v2) {
this.x -= v2.x;
this.y -= v2.y;
return this;
};
// multiply this vector by a scalar and return a new one
Vector.prototype.multiply = function (scalar) {
return new Vector(this.x * scalar, this.y * scalar);
};
// multiply this vector by the scalar
Vector.prototype.multiplyBy = function (scalar) {
this.x = Math.floor(this.x * scalar);
this.y = Math.floor(this.y * scalar);
return this;
};
// scale this vector by scalar and return a new vector
Vector.prototype.divide = function (scalar) {
return new Vector(this.x / scalar, this.y / scalar);
};
// scale this vector by scalar
Vector.prototype.divideBy = function (scalar) {
this.x = Math.floor(this.x / scalar);
this.y = Math.floor(this.y / scalar);
return this;
};
// Utilities
Vector.prototype.copy = function () {
return new Vector(this.x, this.y);
};
Vector.prototype.toString = function () {
return 'x: ' + this.x + ', y: ' + this.y;
};
Vector.prototype.toArray = function () {
return [this.x, this.y];
};
Vector.prototype.toObject = function () {
return {
x: this.x,
y: this.y
};
};
return Vector;
}());