-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector2.js
More file actions
49 lines (48 loc) · 1.05 KB
/
vector2.js
File metadata and controls
49 lines (48 loc) · 1.05 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
function Point(x, y)
{
this.x = x;
this.y = y;
}
Point.prototype.add = function (rhs)
{
return new Vector(this.x + rhs.x, this.y + rhs.y);
}
Point.prototype.sub = function (rhs)
{
return new Vector(this.x - rhs.x, this.y - rhs.y);
}
Point.prototype.toString = function()
{
return "(" + this.x + "," + this.y + ")";
}
Point.prototype.distance = function (p2)
{
return p2.sub(this).mag();
}
function Vector(x, y)
{
Point.call(this, x, y);
}
Vector.prototype = new Point();
Vector.prototype.mag = function()
{
return Math.sqrt(this.x * this.x + this.y * this.y);
}
Vector.prototype.unit = function ()
{
var magnitude = this.mag();
return new Vector(this.x * 1.0 / magnitude, this.y * 1.0 / magnitude);
}
Vector.prototype.dot = function (rhs)
{
return this.x * rhs.x + this.y * rhs.y;
}
Vector.prototype.scale = function (scalar)
{
return new Vector(this.x * scalar, this.y * scalar);
}
Vector.prototype.norm = function ()
{
var magnitude = this.mag();
return new Vector(this.y * 1.0 / magnitude, this.x * -1.0 / magnitude);
}