I am working on a 2d breakout game but I am having problem with the collision. Currently the game is working good with a normal box collision for the ball and the brick.

But for making the ball speed negative/positive I need collision for different sides.

Image: http://i.imgur.com/KSKDN.gif

In the above image when the collisions for the left/right then ballSpeedX will be become "-ballSpeedX" and if its from top/bottm the speedY will be become -speedy.

I can't get this working. I used this for the bottom collision but it makes the ball appear under the brick even if its hit from left/right/top:

if(ball->y <= brick->bottom && ball->y >= brick->top)
   ball->Setxy(ball->x, brick->bottom+1);

Can anyone help?


Is the ball collision volume an AABB (axis-aligned bounding box) or is it a circle (I'll assume AABB)?

If it's an AABB, you'll want to compare opposite sides of the ball and the brick, then reverse the velocity of the ball from the direction it hit:

if(ball->right >= brick.left && ball->top <= brick.bottom && ball->bottom >= brick.top)
    ball->yVelocity *= -1;

When checking for different sides, start with one side, then check against both perpendicular sides, then repeat for all 4 sides. Determine which sides here have collision, then take those sides and figure out which collision you want to use for your reflection.

If the ball is shallower on the vertical collision than the horizontal collision, you'll want to reflect the vertical, and visa versa. If it's a perfect diagonal hit, you can reflect whichever you want, or both.

If the ball is a circle, it will be a bit trickier. You'll be best off looking for a circle-line collision algorithm rather than me trying to explain it when I don't remember it so clearly.

Thanks for your response.

The ball is pretty small so think of it as a rectangle. No need for circle-line collision or anything like that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.