Original Post
For the past year or so, I have been putting together a rendering engine for a 2D game engine that I am attempting to create using SDL. I have spent most of my time optimizing for performance, reorganizing code into an easily reusable form, and adding image, label, animation, shape, button, panel, check box, track bar, etc. classes. Now, I have reached an impasse: proper frame rate management. Over the course of creating the rendering engine, I have tried several methods for controlling frame rate: - I've tried capping the frame rate through timing frame and delaying to match the target FPS:
int ticks = SDL_GetTicks();
while( !quit ) {
mainLoop();
}
if( ( SDL_GetTicks() - ticks < 1000 / FRAMES_PER_SECOND ) ) {
SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - (SDL_GetTicks() - ticks) );
} But this only caused a strange stuttering problem where an object would move smooth for a bit, then kinda stutter, and then would move smooth again, and the process would repeat. - I've using frame independent movement. Basically, I did this:
void moveObjects( float speed_factor ) {
obj->x += vel * speed_factor;
}
int main() {
float ticks = SDL_GetTicks();
while( !quit ) {
moveObjects( (SDL_GetTicks() - ticks) / 1000.f );
ticks = SDL_GetTicks();
render();
}
} This fixed the problem, but I HATE the fact that I have to multiply all velocities by a speed_factor. It causes problems in the way I want to program and I noticed that it caused the objects that were moving to not always end up in the same place even when the condition should be the same... - I also tried a method that I thought up that kinda worked, but kinda didn't:
while( !quit ) {
//if it has been >= the interval_ since the loop was last run, run it
if( SDL_GetTicks() - ticks_ >= interval_ ) {
// over_interval = SDL_GetTicks() - ticks_ - interval_
// ticks = SDL_GetTicks() - (over_interval - ToMultiple(over_interval, interval_))
// = SDL_GetTicks() - SDL_GetTicks() + ticks_ + interval_ + ToMultiple(over_interval, interval_))
// = ticks_ + interval_ + ToMultiple(over_interval, interval_))
ticks_ += interval_ + ToMultiple( SDL_GetTicks()-ticks_-interval_, interval_ );
mainLoop();
}
} This method runs the main loop only after a certain amount of time has passed. It is similar to the first method for capping the fps. This caused the stuttering problem only with any fps cap that wasn't 25. 25 fps ran somewhat smooth, but every once in a while, the stuttering problem would rear its ugly head again. Please, someone give me a way to manage the frame rate without multiplying a factor by all velocities and without capping by timing the frame and delaying!