webgl/public/gl/math/Vec3.js

103 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-01-19 03:43:02 +00:00
export class Vec3 {
constructor(x = 0, y = 0, z = 0) {
this.x = x
this.y = y
this.z = z
}
set(x,y,z) {
this.x = x
this.y = y
this.z = z
return this
}
clone() {
return new Vec3(this.x, this.y, this.z)
}
add(v) {
this.x += v.x
this.y += v.y
2023-01-19 18:39:40 +00:00
this.z += v.z
2023-01-19 03:43:02 +00:00
return this
}
sub(v) {
this.x -= v.x
this.y -= v.y
2023-01-19 18:39:40 +00:00
this.z -= v.z
2023-01-19 03:43:02 +00:00
return this
}
copy(v) {
this.x = v.x
this.y = v.y
this.z = v.z
return this
}
multV(v) {
this.x *= v.x
this.y *= v.y
this.z *= v.z
return this
}
multS(s) {
this.x *= s
this.y *= s
this.z *= s
return this
}
divV(v) {
this.x *= (1 / v.x)
this.y *= (1 / v.y)
this.z *= (1 / v.z)
return this
}
divS(s) {
this.x *= (1 / s)
this.y *= (1 / s)
this.z *= (1 / s)
return this
}
invert() {
this.x = this.x == 0 ? 0 : (1 / this.x)
this.y = this.y == 0 ? 0 : (1 / this.y)
this.z = this.z == 0 ? 0 : (1 / this.z)
return this
}
normalize() {
return this.divS(this.length() || 1)
}
dot(v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
2023-01-19 18:39:40 +00:00
cross(v) {
return this.crossV(this, v)
}
crossV(a, b) {
const ax = a.x, ay = a.y, az = a.z;
const bx = b.x, by = b.y, bz = b.z;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
}
2023-01-19 03:43:02 +00:00
length() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
}