Any game needs to be able to respond to input from the user, and ours is no exception. So lets look at how we can respond to the keys being pressed on the keyboard in order to move a character around on the screen.
There are two events that we are interested in when responding to keyboard input: onkeydown and onkeyup. As the name suggests the onkeydown event is triggered when a key is pressed, and the onkeyup event is triggered when a key is released. Actually, the onkeydown event is triggered repeatedly if you hold a key down, in much the same way as a character would be repeatedly added to a Word document if you held the key down. This doesn’t make any difference to our game, but is worth noting. [code]
We create two new functions in the GameObjectManager to be called when these events are triggered: keyDown and keyUp. These two functions loop through the gameObjects collection and call the keyDown and keyUp functions on the game objects (if the functions have been defined). [code]
The Player class (an Application class) has been created to respond to the keyboard events by defining the keyUp and keyDown functions that the GameObjectManager attempts to call above. The Player class extends the AnimatedGameObject class, because it will move an animated character around on the screen.
The Player class has four Boolean properties, one for each direction it can move (up, down, left and right). [code]
In the update function the Player class will move itself across the screen, stopping at the edges. [code]
Check out the demo here, download the source code here, and browse the code documentation here.