@2112-lab/pathfinder
Version:
Pure JavaScript 3D pathfinding algorithm library for industrial plant pipe routing
83 lines (77 loc) • 2.06 kB
JavaScript
/**
* A simple 3D vector class for internal use
* @class Vector3
*/
export class Vector3 {
/**
* Create a new Vector3
* @param {number} [x=0] - The x component
* @param {number} [y=0] - The y component
* @param {number} [z=0] - The z component
*/
constructor(x = 0, y = 0, z = 0) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Create a copy of this vector
* @returns {Vector3} A new vector with the same components
*/
clone() {
return new Vector3(this.x, this.y, this.z);
}
/**
* Convert the vector to an array
* @returns {Array<number>} Array representation [x, y, z]
*/
toArray() {
return [this.x, this.y, this.z];
}
/**
* Normalize this vector (make it unit length)
* @returns {Vector3} This vector (for chaining)
*/
normalize() {
const length = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
if (length > 0) {
this.x /= length;
this.y /= length;
this.z /= length;
}
return this;
}
/**
* Subtract another vector from this one
* @param {Vector3} v - Vector to subtract
* @returns {Vector3} This vector (for chaining)
*/
sub(v) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
}
/**
* Multiply this vector by a scalar value
* @param {number} scalar - The scalar value to multiply by
* @returns {Vector3} This vector (for chaining)
*/
multiplyScalar(scalar) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
return this;
}
/**
* Add another vector to this one
* @param {Vector3} v - Vector to add
* @returns {Vector3} This vector (for chaining)
*/
add(v) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
}
}