在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
更新了一些代碼。我不測試兩個物體是否正朝着彼此移動。現在我允許球進入對方,然後處理碰撞。 –