Vectors: Vec3

Coordinates, distances, angles and transformations with tera-vec3.

Constructing a vector

tera-vec3 provides three-dimensional vectors. Packet definition fields of type vec3 are represented by objects with x, y, z coordinates and Vec3 methods.

const Vec3 = require('tera-vec3');
const a = new Vec3(1, 2, 3);
const b = new Vec3([1, 2, 3]);
const c = new Vec3({ x: 1, y: 2, z: 3 });

The constructor and vector-taking methods accept three numbers, an array or an object. Missing coordinates default to 0; other values are converted using Number(). For mult/div, missing coordinates default to 1. NaN is accepted; conversion of an unsuitable value such as a Symbol can throw a JavaScript exception.

Mutating methods

These methods modify the current vector and return this, allowing chaining:

Method Operation
add(vector), sub(vector) Component-wise addition/subtraction
mult(vector), div(vector) Component-wise multiplication/division
scale(scalar) Multiply all coordinates by a scalar
rotate(radians) Rotate around Z, leaving Z unchanged
normalize() Set a nonzero vector's length to 1
abs() Absolute value of each coordinate
round() Round coordinates to the nearest integers
const v = new Vec3(1, 2, 3);
v.add({ x: 3 });
// v is now 4,2,3

Methods returning a new object

addN, subN, multN, divN, scaleN, rotateN, normalizeN, absN and roundN perform the same operations but return a new Vec3, preserving the original.

const start = new Vec3(1, 2, 3);
const end = start.addN(1, 1, 1);
// start: 1,2,3; end: 2,3,4

When calculating from event.loc, use an N variant or clone() if you do not intend to mutate the event. Persisting packet changes still requires return true from a normal hook.

Measurements and comparisons

Method Result
length(), sqrLength() Length and squared length
dist2D(vector), sqrDist2D(vector) Distance and squared distance ignoring Z
dist3D(vector), sqrDist3D(vector) Distance and squared distance in 3D
angleTo(vector) XY direction to another point using atan2, in radians
isNaN() Whether any coordinate is NaN
equals(vector) Exact equality of all coordinates
clone() A vector copy
toString() The string x,y,z
const delta = end.subN(start);
if (delta.sqrLength() > 0) delta.normalize();
const nearby = start.sqrDist2D(end) <= 50 * 50;

Edge cases

Normalizing a zero vector produces NaN; check its length first. Division by zero can produce Infinity/NaN. isNaN() does not detect Infinity: use Number.isFinite on each coordinate for external inputs. Current scale uses Number(scalar) || 0, so a nonnumeric string becomes scale 0. Use distance/tolerance rather than equals for approximate comparisons.

Sources: node_modules/tera-vec3/README.md, node_modules/tera-vec3/index.js.