Game Loop Interval

I want to run my game to run in 60 fps. Here's my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

long double t_levelStartTime = 0;
const long double t_GAME_LOOP_INTERVAL = 0.0167;
t_levelStartTime = clock();

while(!window->willExit) //start game loop
{

 long double t_startLoop = clock();
 long double t_levelElapsedTime = (t_startLoop - t_levelStartTime)/CLOCKS_PER_SEC; 

  //some code
  //some more code
  //more code here

  long double t_endLoop = clock();
  long double t_loopElapsed = (t_endLoop - t_startLoop) / CLOCKS_PER_SEC;

  if( t_loopElapsed < t_GAME_LOOP_INTERVAL)
  {
      wait(t_GAME_LOOP_INTERVAL - t_loopElapsed);
  }

}//end game loop 

void Application::wait(long double seconds)
{
	long double endwait;
	endwait = clock() + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}


Am I doing it the right way?
Last edited on
Well, your wait loop doesn't look right.

clock() returns immediately, so your wait function is going to burn a lot of CPU. It will also block the thread.

Are you trying to use WIN32 directly? Or a game library of some kind?
I'm using win32
Ok, then this article might help.

"Writing the Game Loop"
http://www.mvps.org/directx/articles/writing_the_game_loop.htm

It shows how to carry on processing Windows messages while running your game code at a fixed frame rate.

Andy
Last edited on
I tried following what it said in the link. After doing so, the screen kept flickering.
That might have more to do with your drawing code than the game loop itself.

Are you using an offscreen DC to do your drawing?

This code might help provide inspiration. The game code draws to back_dc which is then blt-ed to the screen (game_dc)

http://www.philvaz.com/games/Vazteroids.cpp

(The code is incomplete - no header - but I found it easy enough to get it to run silently, without a joystick by commenting out the DirectSound and joystick code.)
Last edited on
Topic archived. No new replies allowed.