# moving 2D camera

I've got a camera that places the character about a 1/4 way into the screen. The problem I'm having is that when the character moves left the character stays in place now placing the character 3/4 the way into the screen. I tried rectifying the issue with the following code.

``````public Vector2 Position = Vector2.Zero;
public Matrix TransformMatrix
{
get
{
return Matrix.CreateTranslation(new Vector3(-Position, 0f));
}
}

public void LockToTarget(Vector2 charPosition,Rectangle bounds, int screenWidth, int screenHeight, bool direction)
{
float multiplyBy = 0;

if(direction)
multiplyBy = 0.25f;
else if(!direction)
multiplyBy = 0.75f;

Position.X = charPosition.X + (bounds.Width * multiplyBy) - (screenWidth * multiplyBy);
Position.Y = charPosition.Y + (bounds.Height / 2) - (screenHeight / 2);
}
``````

it pretty much gets a boolean value telling it if the character is moving towards the left or right (true = right, false = left), the problem is that the when the character starts moving from on direction to another he simply jumps to the other side of the screen and I'm not sure how to get the camera to move position instead.

any help with this would be really great.

-

This is because you're setting the position of the camera right away. This will make the camera jump from one position to another when you change direction, therefore giving the illusion that your player is jumping.

Since you're using XNA, you could use the magic of MathHelper.Lerp to progressively change from one position to another:

``````const float CAM_LERP_FACTOR = 0.2f; // change this to what you prefer
float newX = charPosition.X + (bounds.Width * multiplyBy) - (screenWidth * multiplyBy);
Position.X = MathHelper.Lerp(Position.X, newX, CAM_LERP_FACTOR);
``````

By playing with the values of the lerp factor (I usually choose a value between 0.1f and 0.2f) you should get an interesting effect.

-
Thanks that is perfect ! – dbomb101 May 22 '11 at 12:45