如何正確地將重力添加到我的物理更新中?
詳細版本:
我有其中用於移動球體平面通用碰撞算法(下面貼供參考)的問題將永遠不會打到這裏未來的衝突將被檢測點。我相信這是由於我有我的物理更新。
我已經設置好了,只有當確定會有未來的碰撞時,重力纔會應用到物體上。因此,在將重力應用於物體之前,首先要完成碰撞檢查。然而,由於總是假定永遠不會有未來的碰撞,所以不會有重力不會被施加。設想一個場景,其值爲
spherePosition = (0, 5, 0)
sphereVelocity = (2, 0, 0)
sphereRadius = 1
planeOrigin = (0, 0, 0)
planeNormal = (0, 1, 0)
這總是假定球體正在移動平面。因此,重力永遠不會被應用。
我的更新比較簡單,如
mAcceleration = mTotalForces/mMass;
Vector3 translation = (mVelocity * fElapsedTime) + 0.5 * mAcceleration * pow(fElapsedTime, 2);
mVelocity += mAcceleration * fElapsedTime;
所以操作的順序大致是
int collisionResult = checkCollision(sphere, plane);
if(collisionResult == 2)
{
sphere.applyGravity(); // Just sets "mAcceleration" to (0, -9.81, 0). Which is then removed by my physics update.
}
sphere.update(timeSlice);
與所有的這樣說,我什麼時候應該在應用重力到我的對象物理更新循環以及如何?如果我在碰撞檢查前應用它,在碰撞檢查過程中,如果我之後要這樣做,如果將來會發生碰撞,應如何調整更新?
碰撞測試基準:
int IntersectMovingSpherePlane(float sphereRadius, const Vector3& sphereCenter, const Vector3& sphereVelocity, const Vector3& planeNormal,
const Vector3& planeOrigin, float planeD, float &t, Vector3 &q)
{
// Compute distance of sphere center to plane
float dist = Vec3Dot(&planeNormal, &sphereCenter) - planeD;
if (fabs(dist) <= sphereRadius) {
// The sphere is already overlapping the plane. Set time of
// intersection to zero and q to sphere center
t = 0.0f;
q = sphereCenter;
return 0;
} else {
float denom = Vec3Dot(&planeNormal, &sphereVelocity);
if (denom * dist >= 0.0f) {
// No intersection as sphere moving parallel to or away from plane
return 1;
} else {
// Sphere is moving towards the plane
// Use +r in computations if sphere in front of plane, else -r
float r = dist > 0.0f ? sphereRadius : -sphereRadius;
t = (r - dist)/denom;
q = sphereCenter + t * sphereVelocity - sphereRadius * planeNormal;
return 2;
}
}
}
我不確定你的問題到底是什麼。你確定不要「只有在沒有碰撞的情況下才施加重力」(換句話說:只要物體不接觸就施加重力)。另外,我總是會應用重力,然後只需對座標設置限制或爲飛機下方的物體添加反作用力。 – kritzikratzi
@kritzikratzi:那是我正在做的一部分。問題是,即使我應用重力,由於我的物理更新(我公佈了代碼示例),它並不重要。你將如何「對座標設置限制或爲飛機下方的物體添加反作用力」。 – mmurphy
一個令人厭惡的方式,很好開始,可能是:始終做sphere.applyGravity()。然後做所有你的物理的東西。之後做sphereCenter.y = max(0,sphereCenter.y); 我仍然不確定你要在這裏做什麼。我還沒有聽說過在某些情況下引力適用的世界。 – kritzikratzi