Game FAQ: How to Create a Chase Camera

Question:

Sorry to be a pain in the backside! but i meant to ask you today as well about your camera in your directx project from last term. Specifically, i was wondering if i could see the way your camera is attached to the character and her movement.

For my project, I’m making a platform game. I’ve already created my scene and have a camera class implemented in the 1st person style, from Luna’s code. Now I want a 3rd person view as well but I’m having problems attaching the camera to the character and having it follow her.

Answer:

tiny_sc_03

Sure. I have a camera class that I use to define the CameraPosition and the CameraLookAt. Then I have a setCameraAngle function which I use to switch between the two camera modes. (Mode 1 = Hood and Mode 2 = Chase)

I had to use some math to calculate the position of the camera based on the position of the model (see my use of sin and cos in the setCameraAngle function below) The use of sin and cos is not very wise, because they are calculation intensive… but it works for the example.

-John

void setCameraAngle()
{
 //Set camera above skinnedMesh head.
 if (options.CAMERA_MODE == 1) {
  //Hood
  theCamera.definePosition(D3DXVECTOR3(
   mSkinnedMesh->position.x,
   mSkinnedMesh->position.y+3.3f,
   mSkinnedMesh->position.z));
  theCamera.defineLookAt(D3DXVECTOR3(
   mSkinnedMesh->position.x
    - sin(mSkinnedMesh->rotation)*D3DX_PI,
   mSkinnedMesh->position.y+3,
   mSkinnedMesh->position.z
    - cos(mSkinnedMesh->rotation)*D3DX_PI));
 };
 //Set Camera behind skinnedMesh head.
 if (options.CAMERA_MODE == 2) {
  //Chase plane
  theCamera.defineLookAt(D3DXVECTOR3(
   mSkinnedMesh->position.x,
   mSkinnedMesh->position.y+2.0f,
   mSkinnedMesh->position.z));
  theCamera.definePosition(D3DXVECTOR3(
   mSkinnedMesh->position.x
    + sin(mSkinnedMesh->rotation)*D3DX_PI,
   mSkinnedMesh->position.y+3.3f,
   mSkinnedMesh->position.z
    + cos(mSkinnedMesh->rotation)*D3DX_PI));
 };
};

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.