Quick Programming Tip: Get Overlapping Area Between Two AABBs.

Quick Programming Tip: Get Overlapping Area Between Two AABBs.

Another Quick Programming Tip comes today. Since I searched through google how to get a the box generated by two overlapping AABBs and found nothing, I found the answer myself and thought it would be good to share it here, so here it goes!

The Question:

You got two AABBs, you know they intersect, and you want to find this inner area, how would you proceed?

2015-04-29 20_16_02-Blender

2015-04-29 20_16_39-Blender
2015-04-29 20_17_22-Blender

Whenever you have two cubes intersecting, their intersection make a new box. This is easily viewable on rects:

With rects it's clearly. The overlapping area, an intersection between A and B is a new rect.

With rects it’s clear. The intersection between A and B is a new rect.

But now, how would one get this box?

The Answer:

First, you’ll need your AABBs in the form

Rectangle {
    Vector3 min;
    Vector3 max;

The idea is simple. View each axis separately.

There’s a small problem we often have to solve and it’s very simple, which is when you have two 1D lines intersecting and you want to know how much of them overlap. Take a look at some more paint art again:

lines overlapping, paint art!

The idea is simple, you’ve probably done it before. Getting the size of this intersection is as simple as:

overlappingSize = min(max1, max2) - max(min1, min2);

Now what if you want to find the line itself? Easy:

start = max(min1, min2);
end = min(max1, max2);

So, now take a look again how we went from cubes, to rects, to lines. The problem is exactly. the. same. But with 3 dimensions instead of 1!

Yeah! Getting the overlapping rect for two rects is as easy as:

Vector2 min = Vector2(max(min1.x, min2.x), max(min1.y, min2.y));
Vector2 max = Vector2(min(max1.x, max2.x), min(max1.y, max2.y));

For AABBs? Yep, you guessed it, the same:

Vector3 min = Vector3(max(min1.x, min2.x), max(min1.y, min2.y), max(min1.z, min2.z));
Vector3 max = Vector3(min(max1.x, max2.x), min(max1.y, max2.y), min(max1.z, max2.z))

Just play attention to the fact that, if you swap your Min and Max vectors, maybe the results will come out wrong! So sort it out.

And that’s it! Was it hard? I hope it’s useful to you somewhere!

Share this:
  • Malo Sal

    totally lost me here. can you state clearly what min and max actually mean?thanks!

    • Gustavok

      min and max attributes are the points that determine the lowest and highest parts of that rectangle.

      min function takes two numbers and return the smallest of them

      max function takes two numbers and return the greatest of them