Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: Cpp :: FPS Indepentent Games

[ FPS Indepentent Games ]

In the old days, when DOS was the first choice for game developers, noone really carred about making Games CPU-Speed indepentent. Depending on the CPU, the games were either too fast or too slow. But in most of modern games, movements of the objects on the screen are calculated CPU-Speed indepentently. An object's movement will be on a P4 1200 as fast as on a PII 350. However if you would run it on a 486 66, there wouldn't much to calculate as you get 1 FPS at maximum.

The basic formula to do this is as follows:

object_pos = object_pos + object_speed * frametime;

This is the basic formula to calculate a movement in the current frame. It's like in physics. object_pos is the object's position. It will by incremented by the object's speed times the frametime. The frametime is the time in ms that the CPU needs to render exactly one frame. Apply this formula to all the objects in your code that move, rotate or do anything else. The movement will then always need the same time, whatever speed the user's processor has.

After this rather theorectical part follows a little demonstration how you could implement it. It will be done under Windows with the timer class STimer from the code section.

#include "STimer.h"
float frametime = 0.0f;
STimer timer;
//The Main Loop function
void Update()
   //Init values
   static float framestart = timer.getTime();
   static float frameend = 0.0f;
   //Repeat this loop until the start of the frame
   //is not the same as the end of frame (prevents on
   //fast machines that a frame will be drawn twice)
      frameend = timer.getTime();
   while (frameend == framestart);
   //calculate frametime
   frametime = frameend - framestart;
   framestart = frameend;
   //frametime is calculated.. do other things
   //Update objects according to the frametime
void UpdateObjects()
   //Function moves and rotates all objects
   //  attention pseudocode .. :-) 
   //Move and rotate all objects in array objects of
   //some struct e.g. MyObject
   for (int i = 0; i < MAX_OBJECTS; i++)
      objects[i].positionX += objects[i].speed * frametime;
      objects[i].rotationZ += objects[i].rotSpeed * frametime;

This little example (which of course will NOT work if you compile it now) shows you how you could implement timing in games. If you know the basic formula above, you know everything. If you want to see an example in action, download the game Memory from the projects section that uses this method.

Question? Comments? M@il me or visit the message board. Happy Coding!

 Last edited 2002-12-07 19:22:54 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0