[英]Java Pong collision detection
Hello I am trying to make a pong game with java and everything works great except collision part. 您好,我正在尝试用Java做一个Pong游戏,除碰撞部分外,其他一切都很好。 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.
我首先使用Bounds类和相交方法来解决此碰撞问题,但该方法仅适用于我画的图片中所示的碰撞情况。
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. 因此,我自己编写了新代码,而不是使用Bounds类,并且成功创建了侧面碰撞检测方法,但是我又很难解决桨叶顶部和底部的碰撞检测。
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: 尝试在一个函数中同时包含两个if语句,如下所示:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.