-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.js
97 lines (79 loc) · 2.45 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
var Vector = function(x, y) {
this.x = x || 0;
this.y = y || 0;
};
// return the angle of the vector in radians
Vector.prototype.getDirection = function() {
return Math.atan2(this.y, this.x);
};
// set the direction of the vector in radians
Vector.prototype.setDirection = function(direction) {
var magnitude = this.getMagnitude();
this.x = Math.cos(angle) * magnitude;
this.y = Math.sin(angle) * magnitude;
};
// get the magnitude of the vector
Vector.prototype.getMagnitude = function() {
// use pythagoras theorem to work out the magnitude of the vector
return Math.sqrt(this.x * this.x + this.y * this.y);
};
// set the magnitude of the vector
Vector.prototype.setMagnitude = function(magnitude) {
var direction = this.getDirection();
this.x = Math.cos(direction) * magnitude;
this.y = Math.sin(direction) * magnitude;
};
// 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;
};
// 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;
};
// 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 *= scalar;
this.y *= scalar;
};
// 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 /= scalar;
this.y /= scalar;
};
// Aliases
Vector.prototype.getLength = Vector.prototype.getMagnitude;
Vector.prototype.setLength = Vector.prototype.setMagnitude;
Vector.prototype.getAngle = Vector.prototype.getDirection;
Vector.prototype.setAngle = Vector.prototype.setDirection;
// 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};
};