Skip to content

Instantly share code, notes, and snippets.

@Pan-Maciek
Created May 4, 2017 18:02
Show Gist options
  • Save Pan-Maciek/269d845f506e7adbf5f491020c212073 to your computer and use it in GitHub Desktop.
Save Pan-Maciek/269d845f506e7adbf5f491020c212073 to your computer and use it in GitHub Desktop.
import { TYPES } from '../core'
/** Class representing a 3 dimensional vector.
* @version 0.0.2
*/
export default class Vec3 extends Float32Array {
constructor(x = 0, y = 0, z = 0) {
super(3)
if (Array.isArray(x) || x.type === TYPES.Vec3) {
[this[0], this[1], this[2]] = x
} else {
this[0] = x
this[1] = y
this[2] = z
}
}
/** Adds v to this vector.
* @param {Vec3|Number[]} v
* @param {Vec3|Number[]=} out Specify target to store operation results.
* @version 0.0.1
*/
add(v, out = this) {
out[0] = this[0] + v[0]
out[1] = this[1] + v[1]
out[2] = this[2] + v[2]
}
/** Returns a new Vec3 with the same x, y and z values as this one.
* @returns {Vec3}
* @version 0.0.1
*/
clone() {
return new Vec3(this)
}
/** Copies the values of the passed vector to this Vec3.
* @param {Vec3|Number[]} input
* @returns {Vec3}
* @version 0.0.1
*/
copy(input) {
this[0] = input[0] || 0
this[1] = input[1] || 0
this[2] = input[2] || 0
return this
}
/** Computes the distance from this vector to v.
* @param {Vec3|Number[]} v
* @version 0.0.1
*/
distanceTo(v) {
return Math.hypot(this[0] - v[0], this[1] - v[1], this[2] - v[2])
}
toJSON() {
return [...this]
}
get x() { return this[0] }
set x(value) { this[0] = value }
get y() { return this[1] }
set y(value) { this[1] = value }
get z() { return this[2] }
set z(value) { this[2] = value }
get type() { return TYPES.Vec3 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment