Coding the Camera for the 3D Game

In the previous sections of this chapter, you created a free-flying 3D camera. You're now going to take that camera and change it to work for the game that you'll be building throughout the rest of this book. If you want to keep your free-flying camera code, you should make a copy of your project to save the existing code that you have written.

If you download the source code for this chapter, you'll find the free-flying camera code in the folder called Flying Camera. The code that is used through the rest of this chapter is located with the source code as well, in the folder called 3D Game.

The game that you're going to build in the rest of this book will use a stationary camera that can rotate a total of 45° in a pitch and 45° in a yaw. Later, you'll be adding some code to send ships flying toward the camera, which you'll have to shoot down.

Because you won't be moving your camera and you won't be rotating in a roll, you can go into the Camera class's Update method and remove the code that enables that functionality.

To do this, remove the following code (which moves the camera forward/backward and side to side) from the Update method of the Camera class:

// Move forward/backward if (Keyboard.GetState( ).IsKeyDown(Keys.W)) cameraPosition += cameraDirection * speed; if (Keyboard.GetState( ).IsKeyDown(Keys.S)) cameraPosition −= cameraDirection * speed; // Move side to side if (Keyboard.GetState( ).IsKeyDown(Keys.A)) cameraPosition += Vector3.Cross(cameraUp, ...

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.