moves / game dev / aabb collision

Box collision (AABB)

Axis-aligned bounding boxes are the cheapest useful collision check: two rectangles overlap unless one is fully to the side of, above, or below the other. To resolve a hit, push the moving box out along the axis with the smaller overlap. Very fast objects can pass through thin walls between frames (tunneling) — use smaller steps or a physics engine like Rapier for that.

#collision#aabb#physics
ts
type Box = { x: number; y: number; w: number; h: number };

function overlaps(a: Box, b: Box) {
  return a.x < b.x + b.w && a.x + a.w > b.x &&
         a.y < b.y + b.h && a.y + a.h > b.y;
}

// Push `a` out of `b` along the axis with the least overlap
function resolve(a: Box, b: Box) {
  const dx = a.x + a.w / 2 - (b.x + b.w / 2);
  const dy = a.y + a.h / 2 - (b.y + b.h / 2);
  const overlapX = (a.w + b.w) / 2 - Math.abs(dx);
  const overlapY = (a.h + b.h) / 2 - Math.abs(dy);
  if (overlapX <= 0 || overlapY <= 0) return;

  if (overlapX < overlapY) a.x += Math.sign(dx) * overlapX;
  else a.y += Math.sign(dy) * overlapY;
}

Related

WWADD — Moves. Stacks. Judgment calls.

FREE REFERENCE · NO LOGIN · NO TRACKING