Hello,
welcome everyone! It's my first post here! :)
I have a question about Collision detection in breakout. I have a little bit of a problem with making it work. I would like to know which side collided. I have this code:
namespace CollisionChecker
{
enum
{
COLLISION_NONE,
COLLISION_TOP,
COLLISION_BOTTOM,
COLLISION_LEFT,
COLLISION_RIGHT,
COLLISION_X,
};
template < class T >
int CheckCollision(Ball& ball, T& block)
{
int collided = COLLISION_NONE;
int ballY = ball.GetY() + ball.GetH()/2;
int ballX = ball.GetX() + ball.GetW()/2;
int r = ball.GetH()/2;
if( (ballY + r < block.GetY())
|| ( ball.GetY() > block.GetY() + block.GetH())
|| (ball.GetX() > block.GetX() + block.GetW())
|| (ball.GetX() + r < block.GetX()) )
{
//No collision;
}
else
{
if(ballY <= block.GetY() - (block.GetH()/2))
{
collided = COLLISION_BOTTOM;
}
//Hit was from below the brick
if(ballY >= block.GetY() + (block.GetH()/2))
{
collided = COLLISION_TOP;
}
//Hit was from above the brick
if(ballX < block.GetX())
{
collided = COLLISION_LEFT;
}
//Hit was on left
if(ballX > block.GetX())
{
collided = COLLISION_RIGHT;
}
//Hit was on right
}
return collided;
}
These conditionals were found in stackoverflow answer. These kinda work, but not quite as I would like them to.
Basically, this isn't this bad. The downside of this collision detection is, that ball can bounce from air, leaving 0 > distance > Ball's radius.
Also, these side detection also sometimes doesn't work as it should. For example, sometimes it collides from side, but bounces upwards, resulting in strange movement that can clear 2 rows of blocks.
And I would like to change paddle bounce later, so that ball would have bounce differently when bouncing from left side, middle, or right side.
Right now I just invert yVel.
Anyway, question is: how can I detect side collision correctly? Also, is there a way to make collision allow ball to bounce directly from block or paddle, instead of leaving this gap?
Thanks in advance guys!