Assessing Keyboard Input for GamesYou know that messages are used heavily throughout the Win32 API to deliver notifications regarding things such as window creation, window destruction, window activation, window deactivation , and so on. You may be glad to find out that this same messaging system is used to deliver notifications regarding key presses on the keyboard. More specifically , the Win32 API defines messages called WM_KEYDOWN and WM_KEYUP that inform you whenever a key has been pressed or released, respectively. These two messages are quite easy to handle in a Windows program, and I'd love to show you how to use them, but there's a problem. The problem is that the standard Windows messaging system is painfully slow when it comes to delivering keyboard messages. Because games rely heavily on responsive controls, it simply isn't acceptable to work with the Windows keyboard messages. The bottom line is that none of your games can support keyboards. Okay, I'm kidding. The truth is that there is always a workaround in game programming, and the slow keyboard messaging problem presents a perfect opportunity for a workaround. If you recall, the timing for the Game Engine was established back in Hour 3, "Creating an Engine for Games," in the WinMain() function. If you recall, the WinMain() function included a program loop that repeated over and over, processing messages for the program. When the function wasn't processing messages, it spent its time running through cycles of the game engine. In other words, the game engine takes advantage of idle time in the main program loop to carry out its game- related tasks . This idle time is what you can use to your advantage when processing key presses and releases on the keyboard.
The idea behind this juiced up approach to keyboard event handling is that instead of sitting around waiting for Windows to eventually send you a keyboard message, you constantly check the keyboard to see if any of the keys you're interested in have been pressed. If so, the game instantly springs into motion and efficiently responds to the key press. If no key is pressed, the game engine hums along with no interruptions. The strategy here is to basically take keyboard processing into your own hands and bypass the standard Windows approach, which ultimately results in much more responsive keyboard controls for your games. You learn how to implement this speedy keyboard handler in code a little later in the hour. For now, let's take a look at how to respond to mouse events. |