Hello I am trying to make a pong game with java and everything works great except collision part. I firstly used Bounds class and intersects method to solve this collision problem but this method only works for the collision case shown on the picture I drew.
So I wrote new code myself instead of using the Bounds class, and I successfully created method for side collision detection but I am again having hard time to solve collision detection for the top and bottom of the paddle.
public boolean collideRight(Ball ball){
if(ball.getLayoutX()+ball.getRadius()>=player.getLayoutX()&&(ball.getLayoutY()+ball.getRadius()>=player.getLayoutY()&&ball.getLayoutY()-ball.getRadius()<=player.getLayoutY()+height)){
return true;
}
else{
return false;
}
}
and This is the method I made for top and bottom collision detection.
public boolean collideRightUpSide(Ball ball){
if((ball.getLayoutX()+ball.getRadius()>=player.getLayoutX()&&ball.getLayoutX()-ball.getRadius()<=player.getLayoutX()+width)&&(ball.getLayoutY()+ball.getRadius()>=player.getLayoutY()&&ball.getLayoutY()-ball.getRadius()<=player.getLayoutY()+height)){
return true;
}
else{
return false;
}
}
Can someone please help me.
Try to include both the if statements in one function which looks something like this:
public boolean collideFunction(Ball ball){
if(ball.getLayoutX()+ball.getRadius()>=player.getLayoutX()&&(ball.getLayoutY()+ball.getRadius()>=player.getLayoutY()&&ball.getLayoutY()-ball.getRadius()<=player.getLayoutY()+height)){
return true;
}
else if((ball.getLayoutX()+ball.getRadius()>=player.getLayoutX()&&ball.getLayoutX()-ball.getRadius()<=player.getLayoutX()+width)&&(ball.getLayoutY()+ball.getRadius()>=player.getLayoutY()&&ball.getLayoutY()-ball.getRadius()<=player.getLayoutY()+height)){
return true;
}
else{
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.