Creating fixed frames per second

Earlier in the book we put in an SDL_Delay function to slow everything down and ensure that our objects weren't moving too fast. We will now expand upon that by making our game run at a fixed frame rate. Fixed frames per second (FPS) is not necessarily always a good option, especially when your game includes more advanced physics. It is worth bearing this in mind when you move on from this book and start developing your own games. Fixed FPS will, however, be fine for the small 2D games, which we will work towards in this book.

With that said, let's move on to the code:

  1. Open up main.cpp and we will create a few constant variables.
    const int FPS = 60;
    const int DELAY_TIME = 1000.0f / FPS;
    
    int main()
    {
  2. Here we define how many frames per second we want our game to run at. A frame rate of 60 frames per second is a good starting point as this is essentially synced up to the refresh rate of most modern monitors and TVs. We can then divide this by the number of milliseconds in a second, giving us the amount of time we need to delay the game between loops to keep our constant frame rate. We need another two variables at the top of our main function; these will be used in our calculations.
    int main()
    {
        Uint32 frameStart, frameTime;
  3. We can now implement our fixed frame rate in our main loop.
    while(TheGame::Instance()->running())
    {
      frameStart = SDL_GetTicks();
    
      TheGame::Instance()->handleEvents();
      TheGame::Instance()->update();
      TheGame::Instance()->render();
    
      frameTime = SDL_GetTicks() - frameStart;
    
      if(frameTime< DELAY_TIME)
      {
        SDL_Delay((int)(DELAY_TIME - frameTime));
      }
    }

First we get the time at the start of our loop and store it in frameStart. For this we use SDL_GetTicks which returns the amount of milliseconds since we called SDL_Init. We then run our game loop and store how long it took to run by subtracting the time our frame started from the current time. If it is less than the time we want a frame to take, we call SDL_Delay and make our loop wait for the amount of time we want it to, subtracting how long the loop already took to complete.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.222.185