BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / vector.js

vector.js

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