Search code examples
algorithmgame-physicsvelocityframe-rate

How can I change velocity by a certain factor for a certain time, while remaining consistent at different framerates?


This is for a game, and I want the velocity of a certain object to decrease at a rate of 98% per frame, when the framerate is 30 frames per second. But, the framerate can be anything between 30 and 60 frames per second. The best solution I came up with was the following:

velocity *= 1.0 - 0.02 * (delta / maxDelta);

So in this case, if the framerate is 30 fps, the velocity will be multiplied by 1.0 - 0.02 * 1.0 = 0.98. If the framerate were 60 fps, the velocity would be multiplied by 1.0 - 0.02 * 0.5 = 0.99. But this is not exactly correct, since at 60 fps, after 2 frames the factor will be 0.9801, not 0.98. Almost there, but not exactly. Is there a simple way to do this more precisely? Thanks.


Solution

  • Imagining for a moment that your FPS will always be 30, can we express the velocity as a straightforward analytic function of the frame number, rather than as an incremental algorithm?
    Yes we can, v = 0.98 ^ frame_number. The ^ is exponentiation.

    Then we can reformulate that as a function of time (in seconds): v = 0.98 ^ (total_time_elapsed * 30). But then we notice this function is continuous and doesn't depend on the frame length.

    If you really need to make it an incremental formula, it can be worked back into v = v * 0.98 ^ (time_elapsed_since_previous_frame * 30).