Skip to Main Content
Learning XNA 3.0
book

Learning XNA 3.0

by Aaron Reed
November 2008
Beginner content levelBeginner
510 pages
16h 24m
English
O'Reilly Media, Inc.
Content preview from Learning XNA 3.0

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning XNA 4.0

Learning XNA 4.0

Aaron Reed
Beginning C# 7 Programming with Visual Studio 2017

Beginning C# 7 Programming with Visual Studio 2017

Benjamin Perkins, Jacob Vibe Hammer, Jon D. Reid

Publisher Resources

ISBN: 9780596154905Supplemental ContentErrata Page