Delta_time locks up my fixed-step game loop


#1

Hello everyone,

currently I am trying to implement a fixed-step game loop to cap my FPS to 60 with SDL_Delay but somehow my game locks up.

2.cc)

Uint32 FPS = 60;
Uint32 MS_PER_SEC = 1000 / FPS;
Uint32 current_time, last_time, delta_time;
current_time = delta_time = 0;

last_time = SDL_GetTicks();

// Poll for Input
while(Platform.Poll())
{
	current_time = SDL_GetTicks();
	delta_time = current_time - last_time;


	// Clear Window
	Renderer.Clear();

	// Update Input
	//...

	// Draw
	Renderer.Draw();
	
	// Update Window
	Renderer.Update();

	last_time = current_time;

	 SDL_Delay(MS_PER_SEC - delta_time);
}

I found out, that

MS_PER_SEC - delta_time

locks my game if a frame takes longer than MS_PER_SEC to process which leads to a negative value and thus to a conversion to unsigned int which as a result is a large value leading to a huge delay.

I tried to delay if and only if:

(MS_PER_SEC - delta_time < MS_PER_SEC)

but this leads to an FPS > 60, in my case 116-118 FPS.

My alternative method is:

1.cc)

while(Platform.Poll())
{
	current_time = SDL_GetTicks(); // Get time of frame begin

	// Clear Window
	Renderer.Clear();

	// Update Input

	// Draw
	Renderer.Draw();
	
	// Update Window
	Renderer.Update();

	last_time = SDL_GetTicks(); // Get time of frame end
	delta_time= last_time - current_time; // calculate frametime

	SDL_Delay(MS_PER_SEC - delta_time);
}

which works but I do not want to use this.
Is not 1.cc and 2.cc equivalent regarding the delta_time or am I missing something?

Is there a way to fix my first attempt?

sincerely yours,
lithium


#2

This is not working:

(MS_PER_SEC - delta_time < MS_PER_SEC)

Try this instead:

(delta_time < MS_PER_SEC)