I have written this code to cap the SDL game to 60 fps, is this the correct way of implementing an fps count?
int fps=60;
int desiredDelta=1000/fps; //desired time b/w frames
while (gameRunning)
{
int starttick=SDL_GetTicks();
// Get our controls and events
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
gameRunning = false;
}
window.Clear();
for(Entity& e: entities)
{
window.Render(e);
}
window.Display();
int delta=SDL_GetTicks()-starttick; //actual time b/w frames
int avgFPS=1000/(desiredDelta-delta); //calculating FPS HERE
if(delta<desiredDelta)
{
SDL_Delay(desiredDelta-delta);
}
std::cout<<avgFPS<<std::endl;
}
In games there are usually two "framerates" to worry about: the framerate of the display and the framerate of your game physics. Ideally, you draw at the native framerate of the display. To do this, ensure you pass the SDL_RENDERER_PRESENTVSYNC
flag to SDL_CreateRenderer()
.
For the physics of your game, you can either measure the time between two rendered frames, and use that as your physics time step, so that you basically match the display framerate. The advantage is that your rates are naturally synced, but the disadvantage is that the physics of the game might suffer from accuracy problems, especially during times when rendering takes so long that the display framerate drops to low values.
Alternatively, you use a fixed framerate for your physics. However, if you do the latter then you have to some how deal with the two framerates not being in sync, but this is not solved by adding SDL_Delay()
s. The usual approach is to have the rendering thread interpolate animations based on physics as necessary.
A more practical issue in your code is that SDL_GetTicks()
gives you the time in milliseconds. That is not very accurate; if your display runs at 60 fps, then one frame takes 16.66666... milliseconds. Your calculation will have an error of up to 1 ms, which is 6.25% of the length of one frame. Depending on the type of game, this can actually be noticable!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With