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

Moving in a First-Person Camera

With the cameraDirection vector being normalized and representing the direction in which the camera is looking, you can easily move the camera forward by simply adding the cameraDirection to the cameraPosition. Doing this will move the camera toward the camera's target in a straight line. Moving backward is just as easy: simply subtract the cameraDirection from the cameraPosition.

Because the cameraDirection vector is normalized (i.e., has a magnitude of one), the camera's speed will always be one. To allow yourself to change the speed of the camera, add a class-level float variable to represent speed:

float speed = 3;

Next, in your Camera class's Update method, add code to move the camera forward and backward with the W and S keys:

// Move forward/backward
if (Keyboard.GetState(  ).IsKeyDown(Keys.W))
    cameraPosition += cameraDirection * speed;
if (Keyboard.GetState(  ).IsKeyDown(Keys.S))
    cameraPosition −= cameraDirection * speed;

At the end of the Update method, you'll want to call your Camera's CreateLookAt method to rebuild the camera based on the changes you've made to its vectors. Add this line of code just above the call to base.Update:

// Recreate the camera view matrix
CreateLookAt(  );

Compile and run the game at this point, and you'll see that when you press the W and S keys, the camera moves closer to and farther from the spaceship. It's important to note what's happening here: in our previous 3D examples, you've moved objects around by changing the ...

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