-
Notifications
You must be signed in to change notification settings - Fork 3
/
Vector2D.js
126 lines (112 loc) · 2.3 KB
/
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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/* author: Jamie Nhu
* email: [email protected]
* blog: http://jamieblog.org
* date: 27th November 2011
*/
function Vector2D(x,y)
{
this.x = x || 0;
this.y = y || 0;//construct Vector2D with param x,y
//set x value
this.setX=function(x)
{
this.x=x;
}
//set y value
this.setY=function(y)
{
this.y=y;
}
//magnitude
this.getLength=function()
{
var length=Math.sqrt(this.x*this.x+this.y*this.y);
return length;
}
//dot product
this.dot=function(vector)
{
return this.x*vector.x+this.y*vector.y;
}
//add vector
this.add=function(vector)
{
this.x+=vector.x;
this.y+=vector.y;
return this;
}
//subtract
this.subtract=function(vector)
{
this.x-=vector.x;
this.y-=vector.y;
return this;
}
//normalize
this.normalize=function()
{
this.x=this.x/this.getLength();
this.y=this.y/this.getLength();
return this;
}
//scale (multiply)
this.scale=function(scale)
{
this.x*=scale;
this.y*=scale;
return this;
}
//has same direction
this.hasSameDirection=function(vector)
{
if(this.isParralel(vector) && vector.x/this.x>0)
{
return true;
}
return false;
}
//check parallel
this.isParallel=function(vector)
{
if(vector.x/this.x == vector.y/this.y)
{
return true;
}
return false;
}
//check perpendicular
this.isPerpendicular=function(vector)
{
if(this.dot(vector)==0)
{
return true;
}
return false;
}
//equal
this.isEqualTo=function(vector)
{
if(this.hasSameDirection(vector) && this.getLength()==vector.getLength())
{
return true;
}
return false;
}
//angle
this.angleBetween = function(vector)
{
return Math.acos(this.dot(vector)/(this.getLength()*vector.getLength()));
}
// invert the vetor
this.invert=function()
{
this.x*=-1;
this.y*=-1;
return this;
}
//to string
this.toString=function()
{
return "Vector2d("+this.x+","+this.y+")";
}
}