segunda-feira, 7 de janeiro de 2013

Game Making : The Game Loop Continued

As I said in my previous post a game is just a software piece with distinct behavior. The way I presented the game loop before was actually a very simplified way of making a game loop. Usually a game loop is more complex than a simple three instruction loop. Most game have a frame limited Game Loop, this means that the game loop will only run a certain number of times per frame, usually 60 FPS.

 There are even more complex architectures than run the Game Loop in multi-threaded way, this means that the Logic Part of the game (Update, Physics, Collision) runs at a different pace than the Rendering loop and on diferent CPU threads.

For example while I can be drawing at 60 FPS (Frame per second), my physics engine can be updating at 120 FPS, this means that for each rendered frame I calculate twice the Logic, this is useful in simulation intensive games (Need for Speed, other vehicle Simulators).

 How can we insert this new information on our game loop?
I won't go in detail of multi-thread Game Loops but the principles are the same. In case you are wondering multi thread game loops are extremely complicate to do as a begginner, you need to be very clear on the way the update and render cycle work to be able to multi thread a game.

public int GameLoop()
    long time = GetTime(); //This just retuns  the current system Time
      long deltaT = GetTime() - time;
       long GameLoopTime = 1/DesiredFrameRate * 1000; 
      Wait(deltaT - GameLoopTime);
      time = GetTime();
      ReadPlayerInput(deltaT) //Keyboard,Mouse,Joystick
      Update(deltaT); //Update the game world (Physics,Animation,Etc)
      Render(deltaT); //Draw Everything to the screen
Most of the code is the same from the previous post we only have a few instructions that are new,

  • GetTime() is just a function that gets the current system time in miliseconds.
  • GameLoopTime is the desired loop speed, for a 60 FPS game it is around 16 miliseconds. This is calculate by deviding 1/FPS * 1000, in our case 1/60  * 1000 = 16.666. So each Game Loop Cycle will take at least 16.66ms.
  • The Wait(waitTime) instruction is just to stop the loop from progressing, it could be implement a Sleep(uint time) in most language. Making the calling thread to sleep for a few milliseconds.
One question that can be lingering, why are we passing the deltaT down to the other methods? Right now, it doesn't really matter that we pass it or not, but it is a good practice that will help solve a lot of nightmares later on.

As again this is just a example, don't take this without a grain of salt, or as the true way to implement, as you can see this is just simple way to explain how to create a simple Game Loop for starting purposes.

As always, if you have any suggestions, comments, or questions, don't hesitate to comment below, and I will try to answer them as soon as possible.

Sem comentários:

Enviar um comentário