Short version:
How can I properly add gravity to my physics update?
Detailed Version:
I am having an issue where the generic collision algorithm for a moving sphere to plane (posted below for reference) will never hit the point where a future collision will be detected. I believe this is due to how I have my physics update.
I have it setup so that only when it will be determined that there will be a future collision, does gravity get applied to the object. So before gravity is applied to an object, the collision check is first done. However, since it is always assumed that there is never any future collision, no gravity is never applied. Imagine a scenario with the values of
spherePosition = (0, 5, 0)
sphereVelocity = (2, 0, 0)
sphereRadius = 1
planeOrigin = (0, 0, 0)
planeNormal = (0, 1, 0)
This would always assume that the sphere is moving parrelel to the plane. As a result, gravity will never be applied.
My update is relatively simple, such as
mAcceleration = mTotalForces / mMass;
Vector3 translation = (mVelocity * fElapsedTime) + 0.5 * mAcceleration * pow(fElapsedTime, 2);
mVelocity += mAcceleration * fElapsedTime;
So the order of operations is roughly
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);
With all of that being said, when should I apply gravity to my object in the physics update loop and how? If I were to apply it before the collision check, it would not matter during the collision check and if I were to do it after, for if there will be a future collision, how should my update be adjusted?
Collision check reference:
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;
}
}
}