AABB-AABB 2D Collision Detection

An example showing how to detect collision between two AABB (Axis-Aligned Bounding Box) in 2D (uses HTML5/JS).

[Get the source code at GitHub]

The idea

Two rectangles that are [XY] axis aligned do not collide if they are separated along an axis. If they overlap on both axes then they collide.

The code

function checkAABBCollision(A, B)
{
  var AisToTheRightOfB = A.getLeft() > B.getRight();
  var AisToTheLeftOfB = A.getRight() < B.getLeft();
  var AisAboveB = A.getBottom() < B.getTop();
  var AisBelowB = A.getTop() > B.getBottom();
  return !(AisToTheRightOfB
    || AisToTheLeftOfB
    || AisAboveB
    || AisBelowB);
}

Brief explanation

If the AABB of an object A is entirely to the right or to the left of the AABB of an object B, then both AABBs are not colliding in the X-axis. When the AABB of an object A is above or below the AABB of an object B, both AABBs are not colliding in the Y-axis.
Only when these four cases are false that both AABBs collide (there is an overlap).
For a 3D version, simply add the Z-axis and you should end up with two more cases to check (A is in front of B, A is behind B).

A note about the code

The code in this page is written for readability and is not optimized (i.e. you don't need to save the checks in variables). You can find the modified and optimized version in main.js as well as in KishiTechJS/aabb.js.

Contact

We hope you enjoyed this article and let us know your thoughts about it! Reach us on Twitter and Facebook.

More collision detection

We also wrote a circle-circle collision detection article, which you can check out here.

Copyright © 2015-2016, Kishimoto Studios. All Rights Reserved.