user717572 user717572 - 6 months ago 9
Android Question

Finding out which side of a 2D AABBxAABB collided?

I'm making a breakout/brick-breaker/arkanoid clone (opengl-es/android) and i've been stuck on my collision detection code for quite some time. As the title suggests: How do I figure out wich side of a brick has been hit by the ball ?

Since I only need to invert the speed in a certain direction, x or y, when a brick is hit I could think of:

if(speedY < 0) : left, upper or right
else : left, bottom or right
if(speedX < 0) : bottom, right or upper
else : bottom, left or upper


however this doesn't bring me far in deciding if it collided vertical or horizontal, and with that, wich direction I should send the ball next.

I've looked at some code examples on the internet, however those often are very vague, complicated or off-topic for me.

Answer

Well, if you know the position of the Brick and the position of the ball you can do tests on each object to determine the side of the brick.

Assuming the standard Java origin in the top-left:

   +----+
( )|    |
   +----+

If the ball's Max-X is < the Min-X of the brick, you know that it has to be on the left side, and vice versa with the right and left. You would also test the Y values for top and bottom collisions.

Of course this assumes you've gotten the collision detection working first.


EDIT


This is an excerpt from my Collision engine, this is just a small bit for an example, but this is how I test if the object is to the left of the thing it's colliding with.

else if ((oCenter.getX() < sCenter.getX()) 
        && ((oCenter.getY() < (sCenter.getY() + sourceHalfHeight)) 
        && (oCenter.getY() > (sCenter.getY() - sourceHalfHeight))))
    return LEFT;

In my example here oCenter is a Point2D and it's the center of the ball. sCenter is a Point2D and it's the center of a rectangular shape. sourceHalfHeight is half the height of the rectangular shape (the object with the center point sCenter).

The Pseudo-code algorithm:

if (the center X of the ball < the center X of the rectangle
        AND the center Y of the ball is BETWEEN the max Y and min Y of the rectangle)
    then the ball is to the LEFT of the rectangle
end if
Comments