Hello guys, i’m working on a game project which is a basic brick breaker type game but i have some trouble in collisions between ball and the bricks. I wanted to revert the balls velocity according to the side of the brick that ball collides with. For this purpose i provided the code below. Here i got a problem, when the ball hits to a brick it just simply reverts the both velocities ( i am aware that my code over detects collisions ), my question is that, is there any better approach that can i follow, because it seems that i cannot handle the 4 side collisions with this approach. Any suggestions will be appreciated, thanks.
if ( ball.getBounds().intersects(brick.getBounds()) )
{
boolean bottom = ball.getVy() < 0 && ball.getY()<= brick.getY() + brick.getHeight();
boolean top = ball.getVy() > 0 && ball.getY()+ball.getHeight()>= brick.getY();
boolean left = ball.getVx() > 0 && ball.getX() + ball.getWidth() >= brick.getX();
boolean right = ball.getVx() < 0 && ball.getX() <= brick.getX()+brick.getWidth();
// Left Side
if (left)
{
ball.setPosX(br.getX() - ball.getWidth()); // reposition ball
ball.setVx(-ball.getVx());
}
// Right Side
else if (right)
{
ball.setPosX(br.getX()); // reposition ball
ball.setVx(-ball.getVx());
}
// Bottom Side
if (bottom)
{
ball.setPosY(brick.getY()+brick.getHeight()); // reposition ball
ball.setVy(-ball.getVy());
}
// Top Side
else if (top)
{
ball.setPosY(brick.getY()-ball.getHeight()); //reposition ball
ball.setVy(-ball.getVy());
}
}