Axis aligned bounding boxes collision: what sides are colliding

4.7k views Asked by At

I'm trying to make an arkanoid-like game, and now I'm facing a problem with the collisions. As usual, the bricks are rectangles (in my case, squares) and the ball is a circle, so it's all about axis aligned bounding boxes.

So far, I've got the trivial collision detection algorithm, but I need to know what side of each brick the ball hits. For example: Collision cases

So far I have an algorithm that checks whether each side has been hit:

up = left = right = down = 0;

if(mouse.left < brick.left && brick.left < mouse.right && mouse.right < brick.right){   
    left = 1;
}

if(brick.left < mouse.left && mouse.left < brick.right && brick.right < mouse.right){
    right = 1;
}

if(mouse.top < brick.top && brick.top < mouse.bottom && mouse.bottom < brick.bottom){
    up = 1;
}

if(brick .top < mouse.top && mouse.top < brick.bottom && brick.bottom < mouse.bottom){
    down = 1;
}

But in the collisions close to the corners, like the third in the image, two flags (for instance, left and down) are set to 1, so I don't know how to decide.

What is usually done in these cases?

1

There are 1 answers

8
GManNickG On BEST ANSWER

Don't just set it to one, set it to the penetration depth:

// why is it named mouse?
if(mouse.left < brick.left && brick.left < mouse.right &&
    mouse.right < brick.right)
{
    left = mouse.right - brick.left;
}

// and so on...

Then when you're done, you can pick whichever is minimum to be your main side.


By the way, I don't think you want that third conditional. Imagine a case like this:

   +-+
   |B|
+--| |--+
|M | |  |
|  | |  |
+--| |--+
   +-+

Here, you have no left or right collision.

(You may also want to review the remaining conditionals for correctness.)