I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back.
This is in my update method
if (keyState.IsKeyDown(Keys.D))
{
camera.Rotation = MathHelper.WrapAngle(camera.Rotation - (rotateScale * elapsed));
}
if (keyState.IsKeyDown(Keys.A))
{
camera.Rotation = MathHelper.WrapAngle(camera.Rotation + (rotateScale * elapsed));
}
if (keyState.IsKeyDown(Keys.W))
{
camera.MoveForward(moveScale * elapsed);
player.Position += new Vector3(0.1f, 0f, 0f);
}
if (keyState.IsKeyDown(Keys.S))
{
camera.MoveForward(-moveScale * elapsed);
player.Position += new Vector3(-0.1f, 0f, 0f);
}
player is the model I'm using. Currently the A and D keys don't do anything with the model.
public class Camera
{
private Vector3 position = Vector3.Zero;
private Vector3 lookAt;
private Vector3 baseCameraReference = new Vector3(0, 0, 1);
private bool needViewResync = true;
private float rotation;
public Matrix Projection { get; protected set; }
private Matrix cachedViewMatrix;
public Vector3 Position
{
get
{
return position;
}
set
{
position = value;
UpdateLookAt();
}
}
public float Rotation
{
get
{
return rotation;
}
set
{
rotation = value;
UpdateLookAt();
}
}
public Matrix View
{
get
{
if (needViewResync)
cachedViewMatrix = Matrix.CreateLookAt(Position, lookAt, Vector3.Up);
return cachedViewMatrix;
}
}
public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip)
{
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
MoveTo(position, rotation);
}
private void UpdateLookAt()
{
Matrix rotationMatrix = Matrix.CreateRotationY(rotation);
Vector3 lookAtOffset = Vector3.Transform(baseCameraReference, rotationMatrix);
lookAt = position + lookAtOffset;
needViewResync = true;
}
private void MoveTo(Vector3 position, float rotation)
{
this.position = position;
this.rotation = rotation;
UpdateLookAt();
}
public Vector3 PreviewMove(float scale)
{
Matrix rotate = Matrix.CreateRotationY(rotation);
Vector3 forward = new Vector3(0, 0, scale);
forward = Vector3.Transform(forward, rotate);
return (position + forward);
}
public void MoveForward(float scale)
{
MoveTo(PreviewMove(scale), rotation);
}
}
I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to