2022-07-28 11:12:55 +00:00
|
|
|
// BetterVector3.js
|
|
|
|
// John Breaux 2022-07-28
|
2022-07-28 12:38:08 +00:00
|
|
|
// Craptastic 3D Vector library
|
2022-07-28 11:12:55 +00:00
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
|
|
class vec3 {
|
|
|
|
constructor(x = 0, y = 0, z = 0) {
|
|
|
|
this.x = x;
|
|
|
|
this.y = y;
|
|
|
|
this.z = z;
|
|
|
|
}
|
|
|
|
|
|
|
|
add(rhs) {
|
|
|
|
return new vec3(this.x + rhs.x, this.y + rhs.y, this.z + rhs.z);
|
|
|
|
}
|
|
|
|
sub(rhs) {
|
|
|
|
return new vec3(this.x - rhs.x, this.y - rhs.y, this.z - rhs.z);
|
|
|
|
}
|
|
|
|
dot(rhs) {
|
|
|
|
return this.x * rhs.x + this.y * rhs.y + this.z * rhs.z;
|
|
|
|
}
|
|
|
|
cross(rhs) {
|
|
|
|
return new vec3(
|
|
|
|
this.y * rhs.z - this.z * rhs.y,
|
|
|
|
this.z * rhs.x - this.x * rhs.z,
|
|
|
|
this.x * rhs.y - this.y * rhs.x
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
magnitude() {
|
|
|
|
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
|
|
|
|
}
|
|
|
|
|
|
|
|
normal() {
|
|
|
|
var m = this.magnitude();
|
2022-07-28 12:38:08 +00:00
|
|
|
if (m === 0) { return null };
|
2022-07-28 11:12:55 +00:00
|
|
|
return new vec3(
|
|
|
|
this.x / m,
|
|
|
|
this.y / m,
|
|
|
|
this.z / m
|
|
|
|
);
|
|
|
|
}
|
|
|
|
normalize() {
|
|
|
|
var m = this.magnitude();
|
|
|
|
if (m === 0) { return null };
|
|
|
|
this.x /= m;
|
|
|
|
this.y /= m;
|
|
|
|
this.z /= m;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
// copy
|
|
|
|
copy() {
|
|
|
|
return new vec3(this.x, this.y, this.z);
|
|
|
|
}
|
|
|
|
// to array
|
|
|
|
a() {
|
|
|
|
return [this.x, this.y, this.z];
|
|
|
|
}
|
|
|
|
// to String
|
|
|
|
toString() {
|
|
|
|
return `{${this.x}, ${this.y}, ${this.z}}`
|
|
|
|
}
|
|
|
|
}
|