← Back to index

Axis-aligned bounding box

The cheapest possible bounding test — just track the minimum and maximum coordinates. The downside: an AABB is not rotation-invariant, so rotating the same shape grows or shrinks the box. Horizontal mouse position controls the rotation.

Pseudocode

minX = +infinity,  maxX = -infinity
minY = +infinity,  maxY = -infinity
for each vertex (x, y):
    if x < minX: minX = x
    if x > maxX: maxX = x
    if y < minY: minY = y
    if y > maxY: maxY = y

Source

let minX =  Infinity, maxX = -Infinity
let minY =  Infinity, maxY = -Infinity
for (const v of poly) {
    if (v.x < minX) minX = v.x
    if (v.x > maxX) maxX = v.x
    if (v.y < minY) minY = v.y
    if (v.y > maxY) maxY = v.y
}
const width  = maxX - minX
const height = maxY - minY