BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / vector.js

vector.js

requestAnimationFrame update
timfa Tim Falken · pushed by timfa · 5 years ago
4e3a04fd History
vector.js 2.1 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.rotate = function(degrees)
110 {
111 var ca = Math.cos(degrees * (Math.PI / 180));
112 var sa = Math.sin(degrees * (Math.PI / 180));
113 return new vector(ca*this.x - sa*this.y, sa*this.x + ca*this.y);
114 }
115
116 this.deltaAngle = function(otherVector)
117 {
118 var a = this.toAngle() * (Math.PI / 180);
119 var b = otherVector.toAngle() * (Math.PI / 180);
120
121 return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI)
122 }
123
124 this.cross = function(otherVector)
125 {
126 return this.x * otherVector.y - this.y * otherVector.x;
127 }
128
129
130 this.getCopy = function()
131 {
132 return new vector(this.x, this.y);
133 }
134}