Skip to content

Instantly share code, notes, and snippets.

@addowhite
Created March 28, 2018 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addowhite/0d0a83d2d46696da651ce4d42f3583a0 to your computer and use it in GitHub Desktop.
Save addowhite/0d0a83d2d46696da651ce4d42f3583a0 to your computer and use it in GitHub Desktop.
Axis-Aligned Bounding Box Intersection
// Class definition
function Rect() {
this.x = this.y = 0;
this.w = this.h = 1;
}
// Given two Axis-Aligned Bounding Boxes, check if any part of one contains any part of the other
function AABBIntersection(rectA, rectB) {
// Local copies of rects so we can modify them
let a = Object.assign({}, rectA), b = Object.assign({}, rectB);
// If the width or height is negative for either bounding box, flip it
if (a.w < 0) a.x -= a.w *= -1;
if (a.h < 0) a.y -= a.h *= -1;
if (b.w < 0) b.x -= b.w *= -1;
if (b.h < 0) b.y -= b.h *= -1;
// Now that the widths and heights are positive, check for sides which overlap or envelope the other rect
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment