我只是想编写一个漂亮的物理游戏。
球碰撞看起来不错,但如果球碰撞太慢,它们就会“粘”在一起。我不知道他们为什么这样做。
这是我的碰撞函数:
private void checkForCollision(ArrayList<Ball> balls) {
for (int i = 0; i < balls.size(); i++) {
Ball ball = balls.get(i);
if (ball != this && ball.intersects(this)) {
this.collide(ball, false);
}
}
}
public boolean intersects(Ball b) {
double dx = Math.abs(b.posX - posX);
double dy = Math.abs(b.posY - posY);
double d = Math.sqrt(dx * dx + dy * dy);
return d <= (radius + b.radius);
}
private void collide(Ball ball, boolean b) {
double m1 = this.radius;
double m2 = ball.radius;
double v1 = this.motionX;
double v2 = ball.motionX;
double vx = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2);
v1 = this.motionY;
v2 = ball.motionY;
double vy = (m1 - m2) * v1 / (m1 + m2) + 2 * m2 * v2 / (m1 + m2);
if (!b)
ball.collide(this, true);
System.out.println(vx + " " + vy);
motionX = vx * BOUNCEOBJECT;
motionY = vy * BOUNCEOBJECT;
}
But this is what happens when they collide with a low speed:
![enter image description here](https://i.stack.imgur.com/krFJx.png)
那么你有什么想法吗?
EDIT:
的更新为Alnitak效果非常好...但仍然存在一个问题...如果我像这样添加重力:
public void physic() {
motionY += GRAVITY; // <= this part (GRAVITY is set to 0.3D)
checkForCollision(screen.balls);
keyMove();
bounceWalls();
posX += motionX;
posY += motionY;
}
他们仍然互相靠近。我认为这是增加重力的错误方法,不是吗?
我认为我在碰撞公式上做错了,因为它们不正确:
!![falling balls](https://i.stack.imgur.com/dk9hQ.png)
然后它们慢慢地沉入地下。
EDIT:发现了一个很棒的教程:http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BounceBalls.html http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html
这是一个常见的问题,因为有时弹跳球的 delta-v 不足以将其带回碰撞区域。
因此,碰撞例程再次反转方向,将其带回另一个球内,无限循环。
您应该向球的位置添加足够的偏移(在碰撞力的方向上),以确保新计算的位置不再发生碰撞。
或者,检查球是否would一旦添加新的就会发生碰撞motion
values:
public boolean intersects(Ball b) {
double dx = b.posX - (posX + motionX); // no need for Math.abs()
double dy = b.posY - (posY - motionY);
double d = dx * dx + dy * dy; // no need for Math.sqrt()
return d < (radius + b.radius) * (radius + b.radius);
}
但你也应该改变ball.intersects(this)
to intersects(ball)
.
它们可能看起来有点太早发生碰撞,但在快速移动的球上,它可能不会被看到。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)