Friday, October 11, 2013

FPS Camera

From my last post I stated that I was going to implement an FPS camera into the game engine. This will be one of many cameras. The various cameras I wish to incorporate are a top down camera, which would be nearly similar to an FPS camera, a third person camera - which follows a user controlled object, and a cinematic camera - an FPS camera with no user input and on rails or static.

Well, today I finished my mouse look WASD controlled FPS camera. The math behind it was pretty simple and only took a couple dozen lines of code from combining my Movement class with my Camera class. Then I put all necessary input translations in regards to the up and right vectors of the camera and the movement of the position vector. Here is a sample of the code:


//sprinting //TODO: remove magic numbers if(keyDown(DIK_LSHIFT)) { mForwardVelocity = 2.0f; mStrafeVelocity = 1.25f; } else { mForwardVelocity = 1.0f; mStrafeVelocity = 0.75f; } //mouse look XMFLOAT2 newPitchHeading( getHeading() + mouseDX() * dt, getPitch() + mouseDY() * dt ); setHeading(newPitchHeading.x); //x rotation is equal to x coordinate mouse movements setRotation(XMFLOAT3( newPitchHeading.x, getRotation().y, getRotation().z )); if(newPitchHeading.y > MINPITCH && newPitchHeading.y < MAXPITCH) { setPitch(newPitchHeading.y); } //keyboard movement if(keyDown(DIK_W)) direction += forward; if(keyDown(DIK_S)) direction -= forward; if(keyDown(DIK_D)) direction += strafe; if(keyDown(DIK_A)) direction -= strafe; direction = XMVector3Normalize(direction); position += direction * mForwardVelocity * dt;







































So essentially we take the mouse x coordinates and make that the heading value of the camera. This is essentially the look left and right with the mouse. The y coordinates of the mouse translate to looking up or down in the world. Conveniently, the camera class takes care of calculating the right and up vectors natively, so we omit it from the update method for the FPS player. We then apply the forward and strafe vectors (up and right) to the direction vector of the player and either increment or decrement depending on player input (W,A,S, or D). Finally, we normalize the direction vector and apply it to the position in relation to the forward velocity and delta time scalars.

Here is a video of the working camera:



No comments:

Post a Comment