Creating a Simple 3D Game with XNA/Adding controls

Taking Keyboard Input
To handle the input to the game we will be taking input from the keyboard, which will then be used to move the fish around the landscape, and escape the game.

Start by creating a new method in your Game1 file called 'HandleInput', and create a new keystate variable. When this method is called, the current state of the keyboard is stored as part of the keystate variable, which then can be accessed by the gamelogic.

Next add the following conditional.

This provides the simplest way to explain how this process works, you can construct as part of any conditional, a way to monitor the position of any key. Place a call to this method in your update code, using the 'gameTime' variable as an argument (which we will use later). With this code in place, you should be able to exit the code at any time by pushing the escape code.

Next, we will place in a similar conditional to use the arrow keys. Add the following lines in your 'HandleInput' method.

In order to make the effect more visible change the following lines in the Update method.

to

And run the code. This should produce an over the shoulder view of your fish as it moves around. The logic behind using the 'ElapsedGameTime' variable, which monitors the difference in time between calls of the update method, compensating for any changes in processing time between frames. If it wasn't for this, the faster your computer the more erratic and faster the controls would be. As it is, it should be consistent between computers. Run the code, and you should see it move around with pushes of the arrow keys.

Finally, to dictate the boundarys of your fish, create a new 'Vector2' variable called 'boundarys', which will dictate the maximum position of the fish in 2D space. Change your arrow handler code as follows.

This should produce a game where the fish only moves to a certain position and stops. Feel free to adjust the movement by monitoring the 'boundary' and 'speed' variable to taste.