4

I'm really new to game development and I've already made a few programs using SDL2. Frame rate wasn't much of an issue since I never planned to release those programs and just used the SDL_RENDER_PRESENTVSYNC to cap the frame rate to 60 (the refresh rate of my monitor). Now I want to make an application I can send to friends and I wanted to know if my frame-rate implementation is any good.

unsigned int a = SDL_GetTicks();
unsigned int b = SDL_GetTicks();
double delta = 0;

while (running)
{
    a = SDL_GetTicks();
    delta += a - b;

    if (delta > 1000/60.0)
    {
        std::cout << "fps: " << 1000 / delta << std::endl;

        Update();
        Render();
        delta = 0;
    }

    b = SDL_GetTicks();
}

I have a good feeling that I've messed up my calculations horribly but many of the other implementations I have found online usually seem pretty long winded. If possible I would like to keep the frame cap implementation within the game loop and as simple as possible. Any help appreciated!

genpfault
  • 51,148
  • 11
  • 85
  • 139
CookingMama
  • 51
  • 1
  • 4
  • [pssst](https://wiki.libsdl.org/SDL_GetPerformanceCounter) – genpfault May 16 '18 at 04:17
  • 1
    Welcome to Stack Overflow! If you believe that the code works correctly, consider presenting your work (with its unit tests) in a more-complete fashion over at [codereview.se]. You'll likely get some suggestions on making it more efficient, easier to read, and better tested. Before you do that, make sure to read [A guide to Code Review for Stack Overflow users](//codereview.meta.stackexchange.com/a/5778) first, as some things are done differently over there - e.g. question titles should simply say what the code *does*, as the question is always, "How can I improve this?". – Toby Speight May 16 '18 at 12:39

1 Answers1

0

You should put the line b = SDL_GetTicks(); inside the if statement and before the Update();. And delta = a - b instead of delta += a - b. And you could also use b=a instead of calling the SDL_GetTicks() function.

while (running)
{
    a = SDL_GetTicks();
    delta = a - b;

    if (delta > 1000/60.0)
    {
        std::cout << "fps: " << 1000 / delta << std::endl;

        b = a;    

        Update();
        Render();
    }
}
Bogdan
  • 461
  • 4
  • 10