Sunday, October 31, 2010

C++ Project - Final Fantasy Battle System pt.3 - Game Loop

So this past week was spent mostly learning the ClanLib GUI system and starting development on a Scene management system that is a basic implementation of a scene graph.

But more on that later. Today I just wanted to follow up on a loose end from last week. Namely the addition of a proper timed game loop to the project.

At some point I will be looking at animations or character movement and I will need the delta time for each frame in order to have proper frame dependent movement.

So the math for this is very simple. I have setup a constant which is my targeted time for each frame:

 static const unsigned int TIME_PER_FRAME = 16; // time per frame in milliseconds  


Since I would like to target 60 fps, I have set the value to 16 milliseconds per frame.

Now in order to calculate the frame time it will look something like this:

- Get system time before game loop
- while (gameLoop)
- Get time before executing game code.
- Calculate deltaTime = (time_before_loop - time_before_executing_game_code)
- GAME CODE
- Get time after game loop.
- Calculate timeToSleep = (TARGET_FRAME_TIME) - (time_before_executing_game_code - time_after_game_loop
- Sleep(timeToSleep)
- loop


Not too bad. And now the actual implementation in our Game class:

      unsigned int lasttime = CL_System::get_time();  
while (m_currentGameState == Running)
{
unsigned int startFrameTime = CL_System::get_time();
int deltaTime = startFrameTime - lasttime;
lasttime = startFrameTime;
DO GAME STUFF HERE
startFrameTime = CL_System::get_time();
int timeToSleep = TIME_PER_FRAME - (startFrameTime - lasttime);
if (timeToSleep > 0)
{
CL_System::sleep(timeToSleep);
}
}


Now I can pass my delta time per frame to my update functions in my IGameComponent class.

 virtual void Update(unsigned int) = 0;  


On other fronts, my Game class is starting to become a little unwieldy especially with all of the GUI stuff making its way in, so I think my next entry will be a bit of a lesson in refactoring.

No comments: