Timers

Heya again folks, I got my animation working now, but I was looking for a
good way to use SDL’s timer.

I have a few ways in mind, but I was wondering if you guys have some code
that has worked well for you?

Sorry if this has been asked before.
-Bryan Arant

Bryan Arant escribi? en el mensaje de noticias
9tv5nu$13d$1 at ftp.lokigames.com

Heya again folks, I got my animation working now, but I was looking for a
good way to use SDL’s timer.

I have a few ways in mind, but I was wondering if you guys have some code
that has worked well for you?

Sorry if this has been asked before.
-Bryan Arant

Well, here’s some code which would not only help for animations but for
games as well…
It keeps a constant (aparent) framerate

Note however that if 1000 is not divisible by FPS then it won’t give you the
exact framerate (can be fixed easily, but I’m just too lazy)

/* set the desired framerate*/
#define FPS 40

/* this is the maximum number of frames to skip in a row*/
#define MAX_FRAME_SKIP 3

/define if you want to have a FPS display/
#define PRINT_FPS

#define TICKS (1000/FPS)

int oticks,ticks,dticks,fpsticks;
int skip_frame, skipped,;

oticks = fpsticks = SDL_GetTicks();
frames = 0;
while (…) { /* whatever you happen to have as a main loop*/
ticks = SDL_GetTicks();

dticks = ticks - oticks;

if ((dticks>TICKS) && (skipped< MAX_FRAME_SKIP)) { /* going too slow?

then skip a frame */
skip_frame = 1;
skipped++;
} else {
skip_frame = 0;
skipped= 0;
if (dticks < 0) { /going too fast? then wait for a few ticks/
SDL_Delay(-dticks);
}
}
oticks += TICKS;

#ifdef SHOW_FPS
if (ticks-fpsticks>=2000) {
frames /=2;
printf(“FPS real: %i simulated: %i\n”,frames,frames-skipped/2);
frames = 0;
skipped = 0;
fpsticks = ticks;
}
frames++;
#endif

// calculate the new position of everything, sprites for example

if (!skip_frame) {
    // draw the sprites and flip screen
}


}