I’m trying to implement a game loop that limits the velocity of execution of my game so it runs on a maximum fps speed. For some reason my code freezes and doesn’t pass the first iteration.
The code is pretty short, it goes like this:
int main(int argc, char *argv[])
{
short int end = 0;
struct Escenario level;
struct Personaje player;
SDL_Surface* screen = NULL;
Uint32 next_frame_tick = 0;
Uint32 sleep_time = 0;
readLevelFile( &level, &player );
screen = initSDL();
showBackground(level, screen );
while(!end){
erasePlayer(&player, screen);
end = manageKeyboardKeys( &player );
detectCollisionsAndMove( level, &player );
showPlayer(player, screen );
next_frame_tick += SKIP_TICKS;
sleep_time = next_frame_tick - SDL_GetTicks();
if( sleep_time > 0 ) SDL_Delay( sleep_time );
}
freeMemory(nivel);
SDL_Quit();
return 0;
}
If I remove the if conditional refering to sleep_time > 0 it doesn’t stuck, but it doesn’t do what I want. I tried to replace that line with the following while:
while( ( next_frame_tick - SDL_GetTicks() ) > 0 )
{
}
It doesn’t work neither, so I run out of ideas…
Anyone can help me a little bit with this ?
Thanks in advance
You are running into an unsigned overflow here:
What happens on this line if
next_frame_tick<SDL_GetTicks()?You just get a difference of two unsigned values, which is going to be not negative, but positive because all the types involved are unsigned.
In this case the value of the difference will be 232 +
next_frame_tick–SDL_GetTicks()instead of justnext_frame_tick–SDL_GetTicks().What you should do instead is: