Repository navigation
Expand file tree
/
Copy pathVec3.js
More file actions
55 lines (55 loc) · 1.33 KB
/
Copy pathVec3.js
File metadata and controls
55 lines (55 loc) · 1.33 KB
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
class Vec3 {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
static fromVec4(vec4) {
this.x = vec4.x;
this.y = vec4.y;
this.z = vec4.z;
}
static fromArray([x, y, z]) {
return new Vec3(x, y, z);
}
add(that) {
return new Vec3(this.x + that.x, this.y + that.y, this.z + that.z);
}
sub(that) {
return new Vec3(this.x - that.x, this.y - that.y, this.z - that.z);
}
scale(scale) {
return new Vec3(this.x * scale, this.y * scale, this.z * scale);
}
normalize() {
const length = this.length();
if (length == 0) return new Vec3(0, 0, 0);
return new Vec3(this.x / length, this.y / length, this.z / length);
}
dot(that) {
return this.x * that.x + this.y * that.y + this.z * that.z;
}
cross(that) {
return new Vec3(
this.y * that.z - this.z * that.y,
this.z * that.x - this.x * that.z,
this.x * that.y - this.y * that.x,
);
}
rotateAroundAxis(axis, angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return this.scale(c)
.add(axis.cross(this).scale(s))
.add(axis.scale(axis.dot(this) * (1 - c)));
}
length() {
const xx = this.x * this.x;
const yy = this.y * this.y;
const zz = this.z * this.z;
return Math.sqrt(xx + yy + zz);
}
distance(that) {
return this.sub(that).length()
}
}