Page 1 of 1

I still want to write a video game!

Posted: Wed Apr 19, 2006 9:02
by BioHazard
I have been wanting to write a video game for a long time now. I have had a lot of ideas stewing in the back of my head and I think I have thought about it enough to make a real attempt at writing a simple side-scroller.

I have one big problem though. The game timer. I can't figure out how to do it. I need to make sure a loop only runs so many times per second no matter how long each cycle takes. I know there is a way to do it, but I don't know how.

If someone knows the secret, please share.

Posted: Thu Apr 20, 2006 12:32
by BioHazard
Well, since I have all this free time where I can't work on any of my good projects, I tried to figure out a scheme for a game timer. I think I got something:

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>

#define TIC_RATE 500
#define TMR_FUNC ((t.time*1000)+t.millitm)

long main(){
	struct timeb t;
	unsigned long _tmr;
	while(1){
		printf("#"); // Timer visualization
	// Get the start time
		ftime(&t);_tmr=TMR_FUNC;
		// Do stuff here
			_sleep(rand()%500); // Just a random delay hack
	// Compare times and wait
		ftime(&t);_tmr=TMR_FUNC-_tmr;
		if(_tmr<TIC_RATE){_sleep(TIC_RATE-_tmr);} // Make sure not to wait a negitive amount
	}return 0;
}
I'm sure there are problems with this so someone please look it over and do some tests. The '#'s should never draw faster than 2 Hz.

Posted: Sat Apr 22, 2006 9:29
by grubber
I'd probably use something like this:

Code: Select all

#define TICDELAY 500

int time_now, last_tic_time = 0;

while (1)
{
  time_now = timer ();

  // Check for a new tic
  if (time_now > last_tic_time + TICDELAY)
  {
    int tic_count = (time_now - last_tic_time) / TICDELAY;

    last_tic_time = time_now;

    // Run as many tics as have passed since last loop
    for (int i = 0; i < tic_count; i++)
    {
      // Do something per-tic, e.g. AI
      do_ai ();
    }
  }

  // Do something per-loop, e.g. rendering
  do_rendering ();
}
Note that this is only example pseude-code and doesn't use any standart functions.

Posted: Mon Apr 24, 2006 11:19
by Graf Zahl
For any type of game timer it is always advisable to use the highest resolution timer available. Standard C library functions are normally not good enough. You never know how well they are implemented. In most cases this has to be system specific.

Posted: Mon Apr 24, 2006 12:14
by BioHazard
But I'm on the right track using time? That's all I really want to know. Is there a better way than using time stuff for timers?

Posted: Thu May 04, 2006 2:53
by Agent ME
Couldn't you possibly look at how DooM does it? Or other open source games like any of the quake games (minus #4, which isn't open-sourced yet).

Posted: Thu May 04, 2006 4:02
by BioHazard
I tried figuring it out from another game, but I didn't know what I was looking for. I'm not very good at understanding other people's source code.