O'Reilly logo

Learning XNA 3.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a 3D Camera

OK, let's put together some code. When dealing with cameras, it often makes sense to create a game component for your camera. This makes it really easy to add cameras to new games (just add the component to the project and then add it in code to the game) and to update the camera and move it around. Create a new game component in your 3D project by right-clicking the project name and selecting Add → New Item.... In the templates list on the right side of the Add New Item screen, select Game Component. Name the component Camera.cs, and click Add (see Figure 9-4).

In the Camera.cs class, add two class-level variables (and appropriate auto-implemented properties) to represent your camera's view and projection matrices:

public Matrix view {get; protected set;}
public Matrix projection { get; protected set; }

Then, change the constructor to accept three Vector3 variables representing the initial position, target, and up vectors for the camera. Also, in your constructor, initialize the view by calling Matrix.CreateLookAt and the projection by calling Matrix.CreatePerspectiveFeldOfView. Here's the complete code for the constructor of the Camera class:

public Camera(Game game, Vector3 pos, Vector3 target, Vector3 up)
    : base(game)
{
    view = Matrix.CreateLookAt(pos, target, up);

    projection = Matrix.CreatePerspectiveFieldOfView(
        MathHelper.PiOver4,
        (float)Game.Window.ClientBounds.Width /
        (float)Game.Window.ClientBounds.Height,
        1, 100);
}

Figure 9-4. Creating a camera game component ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required