BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / util / vector.js

vector.js

run linter with --fix
timfa Tim Falken · pushed by timfa · 2 years ago
80d13a97 History
vector.js 2.2 KiB Download Raw
1class vector
2{
3 x = 0;
4 y = 0;
5
6 constructor (x, y)
7 {
8 this.x = x;
9
10 this.y = y;
11 }
12
13 get length ()
14 {
15 return Math.sqrt((this.x * this.x) + (this.y * this.y));
16 }
17
18 getLength ()
19 {
20 return Math.sqrt((this.x * this.x) + (this.y * this.y));
21 }
22
23
24 toAngle ()
25 {
26 let angle = (Math.atan2(this.y, this.x) * 180 / Math.PI) + 90;
27 if (angle < 0)
28 {angle += 360;}
29 return angle;
30 }
31
32 static fromAngle (angle)
33 {
34 angle = 360 - ((angle + 180) % 360);
35 angle = (angle / 180) * Math.PI;
36 return new vector(Math.sin(angle), Math.cos(angle));
37 }
38
39 normalize ()
40 {
41 var newVector = this.getCopy();
42
43 if (newVector.length != 0)
44 {
45 var length = newVector.length;
46 newVector.x /= length;
47 newVector.y /= length;
48 }
49
50 return newVector;
51 }
52
53
54 lerpTo (otherVector, t)
55 {
56 var delta = otherVector.subtract(this);
57
58 return this.add(delta.stretch(t));
59 }
60
61
62 distanceTo (otherVector)
63 {
64 var dX = this.x - otherVector.x;
65 var dY = this.y - otherVector.y;
66
67 return new vector(dX, dY).length;
68 }
69
70
71 add (otherVector)
72 {
73 var newVector = this.getCopy();
74
75 newVector.x += otherVector.x;
76 newVector.y += otherVector.y;
77
78 return newVector;
79 }
80
81
82 subtract (otherVector)
83 {
84 var newVector = this.getCopy();
85
86 newVector.x -= otherVector.x;
87 newVector.y -= otherVector.y;
88
89 return newVector;
90 }
91
92
93 multiply (otherVector)
94 {
95 var newVector = this.getCopy();
96
97 newVector.x *= otherVector.x;
98 newVector.y *= otherVector.y;
99
100 return newVector;
101 }
102
103
104 divide (otherVector)
105 {
106 var newVector = this.getCopy();
107
108 newVector.x /= otherVector.x;
109 newVector.y /= otherVector.y;
110
111 return newVector;
112 }
113
114
115 stretch (length)
116 {
117 var newVector = this.getCopy();
118
119 newVector.x *= length;
120 newVector.y *= length;
121
122 return newVector;
123 }
124
125 rotate (degrees)
126 {
127 var ca = Math.cos(degrees * (Math.PI / 180));
128 var sa = Math.sin(degrees * (Math.PI / 180));
129 return new vector(ca * this.x - sa * this.y, sa * this.x + ca * this.y);
130 }
131
132 deltaAngle (otherVector)
133 {
134 var a = this.toAngle() * (Math.PI / 180);
135 var b = otherVector.toAngle() * (Math.PI / 180);
136
137 return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI);
138 }
139
140 cross (otherVector)
141 {
142 return this.x * otherVector.y - this.y * otherVector.x;
143 }
144
145
146 getCopy ()
147 {
148 return new vector(this.x, this.y);
149 }
150};