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.
I still want to write a video game!
Moderator: BioHazard
- BioHazard
- Posts: 408
- Joined: Mon Jul 25, 2005 10:02
- Location: Middle of California where there is no air.
- Contact:
- BioHazard
- Posts: 408
- Joined: Mon Jul 25, 2005 10:02
- Location: Middle of California where there is no air.
- Contact:
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:
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.
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;
}
- grubber
- Site Founder
- Posts: 230
- Joined: Wed Jun 29, 2005 18:57
- Location: Czech Republic, Zlin
- Contact:
I'd probably use something like this:
Note that this is only example pseude-code and doesn't use any standart functions.
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 ();
}
- Graf Zahl
- GZDoom Developer
- Posts: 7148
- Joined: Wed Jul 20, 2005 9:48
- Location: Germany
- Contact:
- BioHazard
- Posts: 408
- Joined: Mon Jul 25, 2005 10:02
- Location: Middle of California where there is no air.
- Contact:
- Agent ME
- Posts: 229
- Joined: Mon Jan 02, 2006 12:39
- Contact:
- BioHazard
- Posts: 408
- Joined: Mon Jul 25, 2005 10:02
- Location: Middle of California where there is no air.
- Contact: