Breakout ball collision detection, bouncing against the walls [solved]
- by Sri Harsha Chilakapati
I'm currently trying to program a breakout game to distribute it as an example game for my own game engine. http://game-engine-for-java.googlecode.com/
But the problem here is that I can't get the bouncing condition working properly. Here's what I'm using.
public void collision(GObject other){
if (other instanceof Bat || other instanceof Block){
bounce();
} else if (other instanceof Stone){
other.destroy();
bounce();
}
//Breakout.HIT.play();
}
And here's by bounce() method
public void bounce(){
boolean left = false;
boolean right = false;
boolean up = false;
boolean down = false;
if (dx < 0) {
left = true;
} else if (dx > 0) {
right = true;
}
if (dy < 0) {
up = true;
} else if (dy > 0) {
down = true;
}
if (left && up) {
dx = -dx;
}
if (left && down) {
dy = -dy;
}
if (right && up) {
dx = -dx;
}
if (right && down) {
dy = -dy;
}
}
The ball bounces the bat and blocks but when the block is on top of the ball, it won't bounce and moves upwards out of the game.
What I'm missing? Is there anything to implement? Please help me..
Thanks
EDIT:
Have changed the bounce method.
public void bounce(GObject other){
//System.out.println("y : " + getY() + " other.y + other.height - 2 : " + (other.getY() + other.getHeight() - 2));
if (getX()+getWidth()>other.getX()+2){
setHorizontalDirection(Direction.DIRECTION_RIGHT);
} else if (getX()<(other.getX()+other.getWidth()-2)){
setHorizontalDirection(Direction.DIRECTION_LEFT);
}
if (getY()+getHeight()>other.getY()+2){
setVerticalDirection(Direction.DIRECTION_UP);
} else if (getY()<(other.getY()+other.getHeight()-2)){
setVerticalDirection(Direction.DIRECTION_DOWN);
}
}
EDIT:
Solved now. See the changed method in my answer.