-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector2D.js
44 lines (36 loc) · 997 Bytes
/
vector2D.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
function Vector2D(x, y){
this.x = x;
this.y = y;
}
//Get the angle of a 2D vector
Vector2D.prototype.angle = function(){
if (this.x == 0)
return Math.asin(Math.abs(this.y) / this.y);
else
return Math.atan2(this.y, this.x);
}
//Add vectors
Vector2D.prototype.add = function(w){
return new Vector2D(this.x + w.x, this.y + w.y);
}
//Scalar multiply vectors
Vector2D.prototype.scalarMult = function(t){
return new Vector2D(t * this.x, t * this.y);
}
Vector2D.prototype.subtract = function(w){
return this.add(w.scalarMult(-1.0));
}
//Dot product with the vector w
Vector2D.prototype.dot = function(w){
return (this.x * w.x) + (this.y * w.y);
}
//Project onto the vector w
Vector2D.prototype.project = function(w){
return w.scalarMult(this.dot(w));
}
Vector2D.prototype.modulus = function(){
return Math.sqrt((this.x * this.x) + (this.y * this.y));
}
Vector2D.prototype.normalize = function(){
return new Vector2D (this.x / this.modulus(), this.y / this.modulus());
}