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:
main.cpp
and we will create a few constant variables.const int FPS = 60; const int DELAY_TIME = 1000.0f / FPS; int main() {
int main() { Uint32 frameStart, frameTime;
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.
3.22.181.47