嗨,我正在制作一个BouncingBall程序,其中的球从墙壁弹起并彼此弹开。墙壁很好,但是碰撞是一个问题。我将球存储在ArrayList中,因此可以为每个循环使用a移动任何给定的数字。
我一直无法实现碰撞,看起来很多。我可以得到的最接近的地方是不应该发生随机碰撞的地方。
最近的尝试:物理类来检测碰撞,现在球刚好离开屏幕。
公共课物理{
public static boolean Collision(BouncingBall b, ArrayList<BouncingBall> list){
//boolean collide = false;
for (int i = 0; i < list.size(); i++){
if(b.getXPosition()== list.get(i).getXPosition()){
return true;
}
}
return false;
}
bounce方法本身(在BallDemo类中):
ball.draw();
//above here is code to make balls and add to ArrayList
}
// make them bounce
boolean finished = false;
while (!finished) {
myCanvas.wait(50);
for (BouncingBall ball: balls){
if(Physics.Collision(ball, balls)){
collisionCount(ball);
}
//if ball is out of X bounds bounce it back
else if(ball.getXPosition()>=850 || ball.getXPosition()<0){
ball.collision();
}
//if ball is out of Y bounds bounce it back
else if(ball.getYPosition()>=500 || ball.getYPosition()<0){
ball.yCollision();
}
ball.move();
}
}
}
请注意:由于循环比较第一个球,我知道for循环会发生冲突,但是我尝试从1开始以i开始,但仍然无法正常工作。
最佳答案
由于您正在将每个球与整个列表进行比较,因此它将始终与自身发生冲突。您需要在Collision中添加检查,以查看是否正在与自身进行比较。就像是
if (b == list.get(i)) {
continue;
}