Ive looked up implementing gravity on several sites. Subtract a constant gravity (9.8 * DeltaTime) from the velocity each frame. My problem is, when implementing it as they say, when walking off a ledge the player will float off, not vertically, just accelerates too slowly as he falls.
World->Gravity = -9.8 * PixelsToMeters; // PixelsToMeters = 32 CurrentAcceleration = Vector2(0.0f, World->Gravity); CurrentVelocity = (CurrentAcceleration * DeltaTime) + PrevVelocity; Vector2 halfATSq = currentAcceleration * 0.5f * Square(DeltaTime); Vector2 vt = CurrentVelocity * DeltaTime; CurrentDelta = halfATSq + vt; CurrentPosition += CurrentDelta;
Now the thing is, with the 1/2at^2 + vt + p calculation, the character does fall about 20 meters in 2 seconds, (I think those are the numbers I used, that was a couple hours ago), so it seems the calculations are right. Ive played quite a few side scrollers and none of them have this floating feel.
So, I tried calculating the gravity based on a TimeInAir variable that multiplies the World->Gravity on the third line, instead of DeltaTime.
CurrentVelocity = Vector2(currentAcceleration.X * DeltaTime, currentAcceleration.Y * TimeInAir) + PrevVelocity;
He no longer floats, he falls as expected. Even jumping looks better. However, now he falls 20 meters in 1 second. Ill deal with this, it is only a game and not reality.
Question is, why is it that this works instead of the original code? Or do I have an error somewhere? Because I have to rework the physics code to get it to look right for everything, instead of just using the basic equations. Is it because its all calculated in pixels? Im wondering if I need to add a full gravity to the velocity on the first frame instead of gravity * DeltaTime? This works for falling off a ledge, but not for jumping.
Im testing these questions as I think of them in my code, and still not getting it. These ideas dont seem to work. Thanks for looking and whatever help or ideas you can give!