在Java中,我正在为Android编写一个移动应用程序,用一些我自己编写的类与一些动态球进行交互。重力取决于手机的倾斜度。物理圈碰撞弹出并滑动边界
我注意到当我有一堆球团聚在一个角落里时,他们中的一些会开始抖动,或者有时会在与其他球碰撞时滑动。这可能是因为我在错误的顺序执行步骤?
现在我有一个循环遍历每个球会:
- 辛迭代
- 检查碰撞与其他球
- 检查碰撞对现场界
我应该补充说我与边界发生摩擦,当发生球碰撞时,只是为了失去能量。
这里的碰撞是如何被处理的代码的一部分:
// Sim an iteration
for (Ball ball : balls) {
ball.gravity.set(gravity.x, gravity.y);
if (ball.active) {
ball.sim();
// Collide against other balls
for (Ball otherBall : balls) {
if (ball != otherBall) {
double dist = ball.pos.distance(otherBall.pos);
boolean isColliding = dist < ball.radius + otherBall.radius;
if (isColliding) {
// Offset so they aren't touching anymore
MVector dif = otherBall.pos.copy();
dif.sub(ball.pos);
dif.normalize();
double difValue = dist - (ball.radius + otherBall.radius);
dif.mult(difValue);
ball.pos.add(dif);
// Change this velocity
double mag = ball.vel.mag();
MVector newVel = ball.pos.copy();
newVel.sub(otherBall.pos);
newVel.normalize();
newVel.mult(mag * 0.9);
ball.vel = newVel;
// Change other velocity
double otherMag = otherBall.vel.mag();
MVector newOtherVel = otherBall.pos.copy();
newOtherVel.sub(ball.pos);
newOtherVel.normalize();
newOtherVel.mult(otherMag * 0.9);
otherBall.vel = newOtherVel;
}
}
}
}
}
我们可以看到你迄今为止做了什么吗? – Dan
你在碰撞测试中测试两个物体是否相互靠近?你计算确切的碰撞时间还是允许物体相互移动? – LutzL
更新了一些代码。我不测试两个物体是否正朝着彼此移动。现在我允许球进入对方,然后处理碰撞。 –