Uzay

Vec2

2D 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 } for 2D calculations, screen coordinates, or planar math.

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

import { vec2, Vec2 } from "uzay";

const position = vec2(3, 4);
const doubled = Vec2.scaled(position, 2); // { x: 6, y: 8 }

Operations

All operations return new vectors.

Addition

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

const sum = Vec2.add(a, b);     // { x: 1, y: 1 }
const total = Vec2.add(a, b, a); // { x: 2, y: 1 }

Subtraction

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

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

Scaling

const v = vec2(3, 4);

const doubled = Vec2.scaled(v, 2);  // { x: 6, y: 8 }
const halved = Vec2.scaled(v, 0.5); // { x: 1.5, y: 2 }

Length

const v = vec2(3, 4);
Vec2.length(v); // 5

Normalization

Get a unit vector (length = 1):

const v = vec2(3, 4);
const unit = Vec2.normalized(v); // { x: 0.6, y: 0.8 }

Dot Product

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

Vec2.dot(a, b); // 0 (perpendicular)
Vec2.dot(a, a); // 1 (parallel)

Cross Product (2D)

In 2D, the cross product returns a scalar (the z-component of the 3D cross product):

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

Vec2.cross(a, b); // 1
Vec2.cross(b, a); // -1

This is useful for determining winding order or signed area.

Distance

const a = vec2(0, 0);
const b = vec2(3, 4);

Vec2.distance(a, b);        // 5
Vec2.distanceSquared(a, b); // 25 (faster, no sqrt)

API Reference

Constructor

FunctionSignatureDescription
vec2(x: number, y: number) => Vec2Create a Vec2 object

Constants

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

Operations

FunctionSignatureDescription
Vec2.add(...vectors: Vec2[]) => Vec2Sum of all input vectors
Vec2.subtract(a: Vec2, b: Vec2) => Vec2Vector subtraction a - b
Vec2.length(v: Vec2) => numberVector magnitude
Vec2.scaled(v: Vec2, scalar: number) => Vec2Multiply vector by scalar
Vec2.normalized(v: Vec2) => Vec2Unit vector in same direction
Vec2.dot(a: Vec2, b: Vec2) => numberDot product
Vec2.cross(a: Vec2, b: Vec2) => number2D cross product (scalar)
Vec2.distance(a: Vec2, b: Vec2) => numberEuclidean distance
Vec2.distanceSquared(a: Vec2, b: Vec2) => numberSquared distance (faster)

On this page