Uzay

Vec3

3D vector type and operations

These are lightweight utilities for basic vector math within Uzay. For a more complete, mature, and optimized solution, consider dedicated libraries like gl-matrix, Three.js math, or mathjs.

A plain object type { x, y, z } used throughout Uzay for positions and directions.

There are two exports: vec3 (lowercase) is a helper function for creating vectors, and Vec3 (capitalized) is a namespace containing operations and constants.

import { vec3, Vec3 } from "uzay";

const position = vec3(1, 2, 3);
const doubled = Vec3.scaled(position, 2); // { x: 2, y: 4, z: 6 }

Operations

All operations return new vectors.

Addition

const a = vec3(1, 0, 0);
const b = vec3(0, 1, 0);
const c = vec3(0, 0, 1);

const sum = Vec3.add(a, b);     // { x: 1, y: 1, z: 0 }
const total = Vec3.add(a, b, c); // { x: 1, y: 1, z: 1 }

Subtraction

const a = vec3(5, 3, 1);
const b = vec3(1, 1, 1);

const diff = Vec3.subtract(a, b); // { x: 4, y: 2, z: 0 }

Scaling

const v = vec3(1, 2, 3);

const doubled = Vec3.scaled(v, 2);   // { x: 2, y: 4, z: 6 }
const halved = Vec3.scaled(v, 0.5);  // { x: 0.5, y: 1, z: 1.5 }
const negated = Vec3.scaled(v, -1);  // { x: -1, y: -2, z: -3 }

Length

const v = vec3(1, 2, 2);
Vec3.length(v); // 3

Normalization

Get a unit vector (length = 1) pointing in the same direction:

const v = vec3(3, 4, 0);
const unit = Vec3.normalized(v); // { x: 0.6, y: 0.8, z: 0 }

Dot Product

const a = vec3(1, 0, 0);
const b = vec3(0, 1, 0);

Vec3.dot(a, b); // 0 (perpendicular)
Vec3.dot(a, a); // 1 (parallel to itself)

Cross Product

Get a vector perpendicular to both inputs:

const x = vec3(1, 0, 0);
const y = vec3(0, 1, 0);

const z = Vec3.cross(x, y); // { x: 0, y: 0, z: 1 }

Converting to Array

const v = vec3(1, 2, 3);
const arr = Vec3.asArray(v); // [1, 2, 3]

API Reference

Constructor

FunctionSignatureDescription
vec3(x: number, y: number, z: number) => Vec3Create a Vec3 object

Constants

ConstantValueDescription
Vec3.ZERO{ x: 0, y: 0, z: 0 }Origin / zero vector (frozen)
Vec3.ONE{ x: 1, y: 1, z: 1 }Unit vector in all directions (frozen)

Operations

FunctionSignatureDescription
Vec3.add(...vectors: Vec3[]) => Vec3Sum of all input vectors
Vec3.subtract(a: Vec3, b: Vec3) => Vec3Vector subtraction a - b
Vec3.length(v: Vec3) => numberVector magnitude
Vec3.scaled(v: Vec3, scalar: number) => Vec3Multiply vector by scalar
Vec3.normalized(v: Vec3) => Vec3Unit vector in same direction
Vec3.dot(a: Vec3, b: Vec3) => numberDot product
Vec3.cross(a: Vec3, b: Vec3) => Vec3Cross product
Vec3.asArray(v: Vec3) => [number, number, number]Convert to tuple

On this page