-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector.js
99 lines (85 loc) · 1.76 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
98
99
class Vector
{
constructor( x, y )
{
this.x = x;
this.y = y;
}
get X()
{
return Math.round(this.x);
}
get Y()
{
return Math.round( this.y );
}
mag()
{
var mag = Math.sqrt( Math.pow( this.x, 2 ) + Math.pow( this.y, 2 ) );
return mag;
};
heading()
{
var heading = Math.atan2( this.x, this.y ) / ( Math.PI / 180 );
return heading;
}
add( vector )
{
this.x += vector.x;
this.y += vector.y;
return this;
};
sub( vector )
{
this.x -= vector.x;
this.y -= vector.y;
return this;
}
mult(factor)
{
this.x *= factor;
this.y *= factor;
return this;
}
div(factor)
{
this.x = this.x/factor;
this.y = this.y/factor;
return this;
}
normalize()
{
var m = this.mag();
return (m) ? this.div(m) : this;
}
setMag( mag )
{
var factor = this.normalize().mult(mag);
return this;
}
magSq()
{
return Math.pow(this.x, 2) + Math.pow(this.y, 2);
};
limit( limit )
{
var mSq = this.magSq();
if (mSq > Math.pow(limit, 2) ) {
this.div(Math.sqrt(mSq)).mult(limit);
}
return this;
}
fromAngle( radians, length )
{
if (typeof length === 'undefined') {
length = 1;
}
this.x = length * Math.cos( radians );
this.y = length * Math.sin( radians );
return this;
}
a2r(angle)
{
return angle*Math.PI/180;
}
}