Skip to content

Vector Operations

Vector Operations

function add(a, b):
    return (a.x + b.x, a.y + b.y)

function subtract(a, b):
    return (a.x - b.x, a.y - b.y)

function scale(v, s):
    return (v.x * s, v.y * s)

function length(v):
    return sqrt(v.x^2 + v.y^2)

function normalize(v):
    len = length(v)
    if len == 0: return (0, 0)
    return (v.x / len, v.y / len)

function dot(a, b):
    return a.x * b.x + a.y * b.y

function angleBetween(a, b):
    return acos(dot(normalize(a), normalize(b)))

Vectors represent position, velocity, or direction as an (x, y) pair. Addition/subtraction moves points relative to each other. Scaling changes magnitude without changing direction.

Length comes from the Pythagorean theorem: sqrt(x² + y²). Normalizing divides a vector by its own length, producing a unit vector (length 1) — useful when you want direction only, not magnitude (e.g. moving at constant speed regardless of how far a target is).

Dot product (a.x*b.x + a.y*b.y) measures how aligned two vectors are. It relates to the angle between them via dot(a,b) = |a||b|cos(θ). If both vectors are normalized, the dot product is cos(θ) directly — this is why dot products show up in field-of-view checks, lighting, and "is this in front of me" logic.