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