Skip to main content
Reworded title
Link
Stephane Hockenhull
  • 12.1k
  • 1
  • 27
  • 44

Moving from vsync rendering to accelerated rendering Handling variable frame rate in SDL2

Source Link

Moving from vsync rendering to accelerated rendering

i am creating a game with C++ and SDL2 game engine but i noticed this. I used the Vsync option for rendering, so it'll render at 60fps. If i use this game with another monitor, fps are different (for example 75). I understood that this depends by the monitor frame rate. My monitor is 60Hz and the other is up to 75Hz. The problem is if i disable the Vsync option, Rendering will be accelerated. Fps will increase up to 200 or will be unstable.

Sorry if my english is bad but for example this: I want a block moving 5 pixels per frame. If i have a slow pc the block will move slow. If i have a fast pc the block will move fast.

So i searched for Frame Independent Movement and i pick up this:

movementPerSecond * (timeElapsedInMilliseconds / 1000.0)

I got this formula but i don't know what to use for "movementPerSecond" if i want the same velocity as before. That block will not move 5 pixels per frame but some pixels per second. Before, frames were 60 so the blocks was moving 60*5=300 pixels per second. 300 p/s should be this movement. I disabled Vsync and i tried to do this:

while(1) {
    ...
    // updating coords
    x += 300.f * (timer.get() / 1000.f);
    timer.start();
    // rendering..
    ...
}

i was thinking that this was correct but velocity is faster than before. In some frames, the block doesn't go. i use timer.get() to get the time elapsed since i used timer.start(); i tried to print to the console these values and i got (1, 2, 0, 1, 1, 0, 2, 1). So i think time in one frames is about 1ms. I think however that if milliseconds are 0, movement variation will be 0.. (300*(0/1000) = 0).

I hope you understand what i'm telling. What should i do? Thanks