2D Camera Acceleration/Lag
Posted
by
Cyral
on Game Development
See other posts from Game Development
or by Cyral
Published on 2012-03-29T14:43:17Z
Indexed on
2012/03/29
17:43 UTC
Read the original article
Hit count: 236
I have a nice camera set up for my 2D xna game. Im wondering how I should make the camera have 'acceleration' or 'lag' so it smoothly follows the player, instead of 'exactly' like mine does now. Im thinking somehow I need to Lerp the values when I set CameraPosition. Heres my code
private void ScrollCamera(Viewport viewport)
{
float ViewMargin = .35f;
float marginWidth = viewport.Width * ViewMargin;
float marginLeft = cameraPosition.X + marginWidth;
float marginRight = cameraPosition.X + viewport.Width - marginWidth;
float TopMargin = .3f;
float BottomMargin = .1f;
float marginTop = cameraPosition.Y + viewport.Height * TopMargin;
float marginBottom = cameraPosition.Y + viewport.Height - viewport.Height * BottomMargin;
Vector2 CameraMovement;
Vector2 maxCameraPosition;
CameraMovement.X = 0.0f;
if (Player.Position.X < marginLeft)
CameraMovement.X = Player.Position.X - marginLeft;
else if (Player.Position.X > marginRight)
CameraMovement.X = Player.Position.X - marginRight;
maxCameraPosition.X = 16 * Width - viewport.Width;
cameraPosition.X = MathHelper.Clamp(cameraPosition.X + CameraMovement.X, 0.0f, maxCameraPosition.X);
CameraMovement.Y = 0.0f;
if (Player.Position.Y < marginTop) //above the top margin
CameraMovement.Y = Player.Position.Y - marginTop;
else if (Player.Position.Y > marginBottom) //below the bottom margin
CameraMovement.Y = Player.Position.Y - marginBottom;
maxCameraPosition.Y = 16 * Height - viewport.Height;
cameraPosition.Y = MathHelper.Clamp(cameraPosition.Y + CameraMovement.Y, 0.0f, maxCameraPosition.Y);
}
© Game Development or respective owner