/
vec2.js
144 lines (117 loc) · 2.71 KB
/
vec2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
export default class vec2 {
constructor(x, y) { //no default values cause these needs to be fast.
this.x = x;
this.y = y;
}
static zero() { //static constructor for making empty vectors.
return new vec2(0, 0);
}
static add(a, b) { //adds new vecs and stores them in a new vector.
return new vec2(a.x + b.x, a.y + b.y);
}
add(b) { //modifies self so like a.add(b) changes the vector a. (mem effecient)
this.x += b.x;
this.y += b.y;
return this;
}
static addScalar(a, s) {
return new vec2(a.x + s, a.y + s);
}
addScalar(s) {
this.x += s;
this.y += s;
return this;
}
static clone(a) {
return new vec2(a.x, a.y);
}
clone() {
return new vec2(this.x, this.y);
}
copy(b) {
this.x = b.x;
this.y = b.y;
return this;
}
static cross(a, b) {
return a.x * b.y - a.y * b.x;
}
cross(b) {
return this.x * b.y - a.y * b.x;
}
static crossScalar(a, s, left) {
if (left) {
return new vec2(-s * a.y, s * a.x);
} else {
return new vec2(s * a.y, -s * a.x);
}
}
crossScalar(s, left) {
let x = this.x;
if (left) {
this.x = -s * this.y;
this.y = s * x;
} else {
this.x = s * this.y;
this.y = -s * x;
}
return this;
}
static dot(a, b) {
return a.x * b.x + a.y * b.y;
}
dot(b) {
return this.x * b.x + this.y * b.y;
}
equals(b) {
return a.x === b.x && a.y === b.y;
}
static length(a) {
return Math.sqrt(a.x * a.x + a.y * a.y);
}
length() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
static lengthSquared(a) {
return a.x * a.x + a.y * a.y;
}
lengthSquared() {
return this.x * this.x + this.y * this.y;
}
static negate(a) {
return new vec2(-a.x, -a.y);
}
negate() {
this.x *= -1;
this.y *= -1;
return this;
}
static normalize(a) {
let len = vec2.length(a);
len = 1 / len;
return new vec2(a.x * len, a.y * len);
}
normalize() {
let len = this.length();
len = 1 / len;
this.x *= len;
this.y *= len;
return this;
}
static scale (a, s) {
return new vec2(a.x * s, a.y * s);
}
scale(s) {
this.x *= s;
this.y *= s;
return this;
}
static sub(a, b) {
return new vec2(a.x - b.x, a.y - b.y);
}
sub(b) {
this.x -= b.x;
this.y -= b.y;
return this;
}
}