-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector2.js
More file actions
86 lines (80 loc) · 1.33 KB
/
vector2.js
File metadata and controls
86 lines (80 loc) · 1.33 KB
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
//vector2.js
var Vector2 = function(x, y)
{
this.x = 0;
this.y = 0;
if(x != undefined)
{
this.x = x;
}
if(y != undefined)
{
this.y = y;
}
this.copy = function()
{
return new Vector2(this.x, this.y);
}
this.set = function(newX, newY)
{
this.x = newX;
this.y = newY;
};
this.magnitude = function()
{
return Math.sqrt(this.dot());
};
this.normalize = function()
{
var mag = this.magnitude();
if(mag == 0) return;
this.x /= mag;
this.y /= mag;
};
this.normalized = function()
{
var normCpy = this.copy();
normCpy.normalize();
return normCpy;
};
this.add = function(v2)
{
this.x += v2.x;
this.y += v2.y;
};
this.subtract = function(v2)
{
this.x -= v2.x;
this.y -= v2.y;
};
this.multiplyScalar = function(num)
{
this.x *= num;
this.y *= num;
};
this.rotateDirection = function(angle)
{
var s = Math.sin(angle);
var c = Math.cos(angle);
var dirX = (this.x * c) - (this.y * s);
var dirY = (this.x * s) + (this.y * c);
this.set(dirX, dirY);
};
this.reverse = function()
{
this.set(-this.x, -this.y);
};
this.dot = function(v2)
{
return this.x*this.x + this.y*this.y;
};
this.angle = function()
{
return Math.atan2(this.y, this.x);
};
//Assumes that both vectors are normalized.
this.angleBetween = function(v2)
{
return Math.acos(this.dot(v2));
};
};