BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / util / vector.js

vector.js

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