Once again my OpenGL Pong clone gave me a chance to dig more into the common game programming issues.
This time the problem is SDL and its way to manage user keyboard input: SDL_KeyboardEvent.
The scenario is the following: I have my ball bouncing from one side of the game field to the other and my racket that should move up and down according to some key press events. Really simple. But…
The racket moves too later. I press the key, wait for about a second, and then that white rectangle of pixels decide to obey. Too, too too late.
So what? SDL is slow? No, once again computer is right and I’m wrong.
The issue is on my fps. Scene is rendered too speedy, more than 900 times per second. My handleInput() routine is placed at the very beginning on the game loop and no one knows when exactly the “key pressed” event is fired and catched. I have to tell the truth: I don’t know exactly why this happens, but happens. And I found the trick that solve it.
Delay.
Simply reduce in an artificial way the loop speed and the magic will happens: the keyboard response becomes immediate.
How to do that? Using SDL_Delay and SDL_GetTicks to force the fps below to a maximum rate.
At the beginning of the loop you take the current number of ticks and at the end do the same. Then check the difference with a costant of your choice and delay the loop of the difference. Something like that:
Uint32 start = SDL_GetTicks();
/* do graphic stuff and all the game loop logic */
Uint32 end = SDL_GetTicks();
if(end – start < MAX_FPS_RATE){
SDL_Delay(MAX_FPS_RATE – (end – start));
}
I’ve used 33 as MAX_FPS_RATE to have about 30 fps and all the inputs works great.


