# Fastest AABB collision response

Let’s say I have a flat 2D world of AABBs, what’s the fastest way to respond to collisions in terms of computation?

Right now I build a large AABB (The black outline) by expanding the moving AABB (Red box) through adding the motion to the min/max points.

I then check what collides with that large box (The green boxes). Finally I slide the box as far as I can in each direction, one direction at a time.

Here’s some example code regarding the slide:

``````
// CollisionData holds all the collisions inside of the black outline in the image

// motionY is the desired offset to the entity's y position.
motionPositiveMax = motionY;
motionNegativeMin = motionY;
for (int i = 0; i < CollisionData.size; i++) {
AxisAlignedBB collision = CollisionData.collisions[i];
// Check collision in the X axis
if (tmaxX > collision.minX && tminX < collision.maxX) {
motionPositiveMax = Math.min(motionPositiveMax, collision.minY - tmaxY);
motionNegativeMin = Math.max(motionNegativeMin, collision.maxY - tminY);
}
}
// Flag if motionY is positive
if (posY) {
motionNegativeMin = motionPositiveMax;
}
// Slide the entity's bounding box in the y axis
entity.minY += motionNegativeMin;
entity.maxY += motionNegativeMin;

// motionX is the desired offset to the entity's x position.
motionPositiveMax = motionX;
motionNegativeMin = motionX;
for (int i = 0; i < CollisionData.size; i++) {
AxisAlignedBB collision = CollisionData.collisions[i];
// Check collision in the Y axis
if (entity.maxY > collision.minY && entity.minY < collision.maxY) {
motionPositiveMax = Math.min(motionPositiveMax, collision.minX - tmaxX);
motionNegativeMin = Math.max(motionNegativeMin, collision.maxX - tminX);
}
}
// Flag if motionX is positive
if (posX) {
motionNegativeMin = motionPositiveMax;
}
// Slide the entity's bounding box in the x axis
entity.minX += motionNegativeMin;
entity.maxX += motionNegativeMin;
``````

For those using Swept AABB Collision http://www.gamedev.net/page/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084, this is basically the “slide” collision response, except this does significantly less work.

This method I’m using for 3D collision and it’s working well. It makes a number of assumptions, such as the collisions are calculated frequently and aren’t moving exceptionally fast because it’s more of a best guess on when the resulting position is rather than the correct position. Worst case, such as with fast moving projectiles, ray tracing can be used instead.

I’m curious if anyone has a faster method.