BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / vector.js

vector.js

remove outdated comments
timfa Tim Falken · pushed by timfa · 8 years ago
61a474fb History
vector.js 2.0 KiB Download Raw
1
2
3function vector(x, y)
4{
5
6 this.x = x;
7
8 this.y = y;
9
10
11 this.length = function()
12 {
13 return Math.sqrt((this.x * this.x) + (this.y * this.y));
14 }
15
16
17 this.toAngle = function()
18 {
19 return (Math.atan2(this.y, this.x) * 180 / Math.PI) + 90;
20 }
21
22
23 this.normalize = function()
24 {
25 var newVector = this.getCopy();
26
27 if(newVector.length() != 0)
28 {
29 var length = newVector.length();
30 newVector.x /= length;
31 newVector.y /= length;
32 }
33
34 return newVector;
35 }
36
37
38 this.lerpTo = function(otherVector, t)
39 {
40 var delta = otherVector.subtract(this);
41
42 return this.add(delta.stretch(t));
43 }
44
45
46 this.distanceTo = function(otherVector)
47 {
48 var dX = this.x - otherVector.x;
49 var dY = this.y - otherVector.y;
50
51 return new vector(dX, dY).length();
52 }
53
54
55 this.add = function(otherVector)
56 {
57 var newVector = this.getCopy();
58
59 newVector.x += otherVector.x;
60 newVector.y += otherVector.y;
61
62 return newVector;
63 }
64
65
66 this.subtract = function(otherVector)
67 {
68 var newVector = this.getCopy();
69
70 newVector.x -= otherVector.x;
71 newVector.y -= otherVector.y;
72
73 return newVector;
74 }
75
76
77 this.multiply = function(otherVector)
78 {
79 var newVector = this.getCopy();
80
81 newVector.x *= otherVector.x;
82 newVector.y *= otherVector.y;
83
84 return newVector;
85 }
86
87
88 this.divide = function(otherVector)
89 {
90 var newVector = this.getCopy();
91
92 newVector.x /= otherVector.x;
93 newVector.y /= otherVector.y;
94
95 return newVector;
96 }
97
98
99 this.stretch = function(length)
100 {
101 var newVector = this.getCopy();
102
103 newVector.x *= length;
104 newVector.y *= length;
105
106 return newVector;
107 }
108
109 this.deltaAngle = function(otherVector)
110 {
111 var a = this.toAngle() * (Math.PI / 180);
112 var b = otherVector.toAngle() * (Math.PI / 180);
113
114 return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI)
115 }
116
117 this.cross = function(otherVector)
118 {
119 return this.x * otherVector.y - this.y * otherVector.x;
120 }
121
122
123 this.getCopy = function()
124 {
125 return new vector(this.x, this.y);
126 }
127}