-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.js
71 lines (58 loc) · 1018 Bytes
/
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
this.magnitude = function( v )
{
return Math.sqrt( v.x * v.x + v.y * v.y );
}
this.normalize = function( v )
{
var m = this.magnitude( v );
if ( m > 0 )
{
return this.divideBy( v, m );
}
return v;
}
this.distance = function( v1, v2 )
{
var dx = v1.x - v2.x;
var dy = v1.y - v2.y;
return Math.sqrt( dx*dx + dy*dy );
}
this.subtractFrom = function( v1, v2 )
{
var result = {};
result.x = v1.x - v2.x;
result.y = v1.y - v2.y;
return result;
}
this.divideBy = function( v, n )
{
var result = {};
result.x = v.x / n;
result.y = v.y / n;
return result;
}
this.addTo = function( v1, v2 )
{
var result = {};
result.x = v1.x + v2.x;
result.y = v1.y + v2.y;
return result;
}
this.multiplyBy = function( v, n )
{
var result = {};
result.x = v.x * n;
result.y = v.y * n;
return result;
}
this.limitTo = function( v, max )
{
var result = v;
var m = this.magnitude( v );
if ( m > max )
{
result = this.normalize( v );
result = this.multiplyBy( result, max );
}
return result;
}