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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 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(); if (left) { ball.setPosX(br.getX() - ball.getWidth()); ball.setVx(-ball.getVx()); }
else if (right) { ball.setPosX(br.getX()); ball.setVx(-ball.getVx()); }
if (bottom) { ball.setPosY(brick.getY()+brick.getHeight()); ball.setVy(-ball.getVy()); } else if (top) { ball.setPosY(brick.getY()-ball.getHeight()); ball.setVy(-ball.getVy()); } } |