BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / util / vector.js

vector.js

format
timfa Tim · pushed by timfa · 4 years ago
24db7846 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 var length = newVector.length;
45 newVector.x /= length;
46 newVector.y /= length;
47 }
48
49 return newVector;
50 }
51
52
53 lerpTo(otherVector, t)
54 {
55 var delta = otherVector.subtract(this);
56
57 return this.add(delta.stretch(t));
58 }
59
60
61 distanceTo(otherVector)
62 {
63 var dX = this.x - otherVector.x;
64 var dY = this.y - otherVector.y;
65
66 return new vector(dX, dY).length;
67 }
68
69
70 add(otherVector)
71 {
72 var newVector = this.getCopy();
73
74 newVector.x += otherVector.x;
75 newVector.y += otherVector.y;
76
77 return newVector;
78 }
79
80
81 subtract(otherVector)
82 {
83 var newVector = this.getCopy();
84
85 newVector.x -= otherVector.x;
86 newVector.y -= otherVector.y;
87
88 return newVector;
89 }
90
91
92 multiply(otherVector)
93 {
94 var newVector = this.getCopy();
95
96 newVector.x *= otherVector.x;
97 newVector.y *= otherVector.y;
98
99 return newVector;
100 }
101
102
103 divide(otherVector)
104 {
105 var newVector = this.getCopy();
106
107 newVector.x /= otherVector.x;
108 newVector.y /= otherVector.y;
109
110 return newVector;
111 }
112
113
114 stretch(length)
115 {
116 var newVector = this.getCopy();
117
118 newVector.x *= length;
119 newVector.y *= length;
120
121 return newVector;
122 }
123
124 rotate(degrees)
125 {
126 var ca = Math.cos(degrees * (Math.PI / 180));
127 var sa = Math.sin(degrees * (Math.PI / 180));
128 return new vector(ca * this.x - sa * this.y, sa * this.x + ca * this.y);
129 }
130
131 deltaAngle(otherVector)
132 {
133 var a = this.toAngle() * (Math.PI / 180);
134 var b = otherVector.toAngle() * (Math.PI / 180);
135
136 return Math.atan2(Math.sin(a - b), Math.cos(a - b)) * (180 / Math.PI)
137 }
138
139 cross(otherVector)
140 {
141 return this.x * otherVector.y - this.y * otherVector.x;
142 }
143
144
145 getCopy()
146 {
147 return new vector(this.x, this.y);
148 }
149};