Saturday, August 27, 2011

Fixed Frequency Uncoupled Game Loop

Version 2 of the Bouncy Rectangle program has a refactored game loop engine. After looking around at ways to separate the rate that events happen in the game from the rendering speed of the system running the program I went with an approach called Fixed-Frequency Uncoupled method. Where the game engine will run certain events at fixed frequency, while uncoupling a second module of the program that does the rendering using as much CPU speed is available. To make it interesting I also added an AI opponent, which is another blue square that follows the player around the screen. (No music this time).

To implement multi-threading I used POSIX threads (-pthreads). The fixed frequency game logic would update the game state based on user input and the physics of the moving rectangle "characters". It would then sleep for 100 ms, basically updating the game state 10 times a second.

The render loop was in the main thread and would both update the screen with the updated game state as well as do some animation interpolation based on the trajectories of the rectangles from the last game state. This also had to trap any user input (keyboard keys) and then update the game state with these inputs for when the fixed-frequency thread would next check it. To avoid synchronization issues, I used mutexes when in critical sections that accessed the shared variables containing game state info. The render loop will run as fast as the system it runs on, on my box it was humming along at 140 fps.

This is a high level diagram of the separation of the game logic:

References:

No comments:

Post a Comment