2
\$\begingroup\$

I found a formula for gravity and jumping in this article: http://error454.com/2013/10/23/platformer-physics-101-and-the-3-fundamental-equations-of-platformers/

formula for gravity

formula for jump velocity

I implemented this formula and proceeded to do some test calculations, but they yield incorrect results. I expected the outcome to be 4, but the test resulted in 3.8. What am I doing wrong? How do I get the number 4?

test output log

float deltaTime = 1f / 50f;

float maxJumpHeight = 4;
float timeToApex = 0.44f;
float gravity = (2 * maxJumpHeight) / (timeToApex * timeToApex);

float jumpHeight = 4;
float jumpVelocity = (float)Math.Sqrt(2 * gravity * jumpHeight);

float velocity = -jumpVelocity;
float position = 0;

while (velocity < 0)
{
    velocity += gravity * deltaTime;
    position += velocity * deltaTime;
    Console.WriteLine("Position = {0}", position);
}
\$\endgroup\$
3
\$\begingroup\$

It's because of the discreet time and the way you integrate. Because you step time forward at 1/50 of a second you're not guaranteed to hit the actual apex of 4.0, the delta is just not granular enough. (Try setting the delta time to 1/5000 and you'll see that it gets closer to 4, obviously that won't work for your game but it will show you the effect).

Depending on the integration method you use you will get varying degrees of correctness, with Euler integration being quite bad when it comes to accuracy.

This article has a nice explanation on why integration might lose precision; http://www.marekfiser.com/Projects/Real-time-visualization-of-3D-vector-field-with-CUDA/4-Vector-field-integrators-for-stream-line-visualization

\$\endgroup\$
0
\$\begingroup\$

I was able to achieve a precise gravity simulation by applying the 'correction' said in this article: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html

Basicaly it consists in dividing the gravity by 2 in the very first frame/iteration when adding it to velocity.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .