@papit/box-intersection
v0.0.2
Published
Axis-aligned box intersection in 2D and 3D: AABB overlap, point-in-box and ray vs box. Reach for it as a fast first collision test.
Maintainers
Readme
@papit/box-intersection
Axis-aligned box intersection in 2D and 3D: AABB overlap, point-in-box and ray vs box. Reach for it as a fast first collision test.
Installation
npm install @papit/box-intersectionUsage
import { AABB, isPointInRectangle, rayBox } from "@papit/box-intersection";
AABB({ x: 0, y: 0, w: 10, h: 10 }, { x: 5, y: 5, w: 10, h: 10 });
// { x: 5, y: 5, w: 5, h: 5 }
isPointInRectangle({ x: 7, y: 7 }, { x: 0, y: 0, width: 10, height: 10 }); // trueAdd z and d (or depth) and the same calls work in 3D:
import { AABB, rayBox } from "@papit/box-intersection";
import { Vector3 } from "@papit/vector";
const a = { x: 0, y: 0, z: 0, w: 10, h: 10, d: 10 };
const b = { x: 5, y: 5, z: 5, w: 10, h: 10, d: 10 };
AABB(a, b); // { x: 5, y: 5, w: 5, h: 5, z: 5, d: 5 }
const hit = rayBox(new Vector3(-5, 5, 5), new Vector3(1, 0, 0), a);
// { t: 5, point: Vector3(0, 5, 5), normal: Vector3(-1, 0, 0) }API
All functions are O(1).
AABB
AABB(a: Rectangle, b: Rectangle): Overlap | falseThe overlapping region as { x, y, w, h } (plus z, d when both boxes are 3D), or false. Touching faces count as overlap with size 0. The output always uses the short size names.
isPointInRectangle
isPointInRectangle(point: Point, box: Rectangle): booleanInside or on the edge. z is checked only when both the box and the point have one.
rayBox
rayBox(origin: Point, direction: Point, box: Rectangle): { t, point, normal } | falseSlab test, 3D when the box has a z.
| Field | Description |
| --- | --- |
| t | distance in units of direction's length: point = origin + t * direction |
| point | first hit, a Vector2 or Vector3 |
| normal | outward face normal at the hit |
A ray starting inside hits at t = 0 with a zero normal. A zero direction only hits from inside.
Types
type Rectangle = { x, y, w, h } | { x, y, width, height } // plus optional z, d / depth
type Point = { x: number; y: number; z?: number } // Vector2 / Vector3 fitLicense
Licensed under the @Papit License 1.0 Copyright (c) 2024 Henry Pap (@onkelhoy)
Key points
- ✅ Free to use in commercial projects
- ✅ Free to modify and distribute
- ✅ Attribution required
- ❌ Cannot resell the component itself as a standalone product
See the LICENSE file for full details.
Related
@papit/circle-intersection: circles and spheres@papit/gjk: rotated boxes and any other convex shape@papit/sat: 2D polygons with contact normal
