Search code examples
c++sdlgame-physics

Implementing Delta Time (In Seconds) into Velocity


Using C++, SDL2, and Vulkan, I'm trying to implement delta time into my game movement by multiplying movement speed by delta time like so:

velocity += speed * dt;

I've got this code below which apparently calculates delta time dt, but I don't really understand much of it and what I need to modify in order to be able to update the velocity by pixels per second.

EDIT: SDL_GetTicks() returns the current time by milliseconds.

deltaTime = (SDL_GetTicks() - lastTime) * (TARGET_FPS / 1000.f);

if (deltaTime > TARGET_DELTATIME)
    deltaTime = TARGET_DELTATIME;
    
lastTime = SDL_GetTicks();

With a given TARGET_FPS (lets say 60 for now), and a speed of 50 pixels per second, how can I update the velocity correctly?


Solution

  • Never change the velocity, instead let your physics calculations include delta time as a component. In general, multiply by (delta_since_last_frame/arbitrary_constant_you_tune).

    EDIT* For example: position += velocity * (delta * ARBITRARY_TUNING_CONSTANT); It's tempting to set ARBITRARY_TUNING_CONSTANT to TARGET_FPS/1000.0f, which you can, but set it to whatever lets you set your velocity values to something that feels intuitive to you.

    Define a sort of base velocity value, for example let's say you want a velocity of 10.0 to represent moving at 50 px per second. Then set arbitrary_constant_you_tune to make this true. (the arbitrary constant is CONSTANT always, just set once during program initialization or config). Also once you really write it in code, use multiplication rather than division (e.g. prefer 0.2 to 1/5) because multiplication is faster to compute.

    One nuance to this: be aware that the game physics will be slightly different for people at different frame rates if you use delta time in a simple manner like this. For example, maximum jump height will be different, 2 games running side-by-side at different frame rates will show a different course of events, etc. Just be aware of this as you tune your game physics and game logic