2
$\begingroup$

While gravity in real life is continuous, computers are limited to discrete calculations.

Therefore, a seemingly correct projectile simulation inevitably drifts off.

For example:

// Repeat once per frame
position += velocity * deltaTime;
velocity += gravity * deltaTime;

Graphed, compared to the actual projectile formula Two datasets merged. While they look equal at first, the discrete data drifts off over time.

$\endgroup$
1
1
$\begingroup$

This is an example of Euler's Method

Using differentiation, you can find a better formula. Since discrete calculations only "drift" if they are non-linear, you only need to alter the position/time calculation.

// Repeat once per frame
position += velocity * deltaTime + gravity * Math.pow(deltaTime, 2.0) / 2.0;
velocity += gravity * deltaTime;

Even large timesteps align perfectly with the continuous graph:

Improved code, merged with a continuous graph. The points are directly on the line

$\endgroup$
1
  • $\begingroup$ what happens if you compute the velocity with gravity first and then update the position? $\endgroup$
    – Max N
    Jan 20 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.