The Main Loop

Most Windows software waits for the user to do something before they run any code. If the mouse isn't moving and the keyboard isn't being hammered, the application is completely idle. This is good for things like Microsoft Word and other applications because you can have a bunch of them up and running without a large CPU overhead. Games are completely different. Games are simulations that have a life of their own. Without player input, they'll happily send some horrific creature over to start pounding on your character's skull. That will probably motivate a few key presses.

The system that controls this ongoing activity is the main loop, and it has three major components: grabbing and translating player input, simulating the game world, and rendering the screen.

Player input is mapping changes in input devices like the mouse, a joystick, or the keyboard into game events. An example of this might be something like a keyboard event, such as pressing the "W" key, translated into a game event such as "add one meter per second to the player's forward speed." Notice that the event wasn't "move forward"—that implies that the game state is changed from within the user interface code, which would be a big mistake. The reasons for this are discussed in more detail in Chapter 5.

A body of code that simulates the world is usually broken down into discrete bits of very simple code, such as a bit of code to move an object along a linear path or rotate it at a given angular velocity. These bits of code can be combined to act on a single game object, which will have the effect of combining these movements. These bits of code are usually organized into classes, and can be instantiated for any game object. These classes can even have dependencies on each other, where one will wait for another to complete before starting. A good example of this is something you might use for a Molotov cocktail: one class tracks the parabolic movement of any game object until it collides with something, and another class creates a fireball explosion. Your game can string these classes together to create some amazingly cool effects.

The game renderer's job is drawing the screen as fast as it possibly can. It is decoupled from both the user interface and the game simulation code so that it will scale appropriately on different computers with a wide range of CPU power and under different game conditions. Generally, lower-end CPUs will cut expensive features to run at the best frame rate they can, but you'll always have a varying frame rate. Different game conditions will also place varying loads on even the best CPUs, and decoupling the renderer from the rest of the game code is the best way to manage this problem.

Game Coding Complete
Game Coding Complete
ISBN: 1932111751
EAN: 2147483647
Year: 2003
Pages: 139 © 2008-2017.
If you may any questions please contact us: