In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this:

public void RepositionCamera()
   // For the example I don't consider world rectangle bounds
   current_camera.Position =
      new Vector2(
         player_.Position.X - 250,
         player_.Position.Y - 100));

The problem here is that when I press very rapidly "left-right-left-rigth..." the camera does a very annoying effect, it seems an eartquake.

I think this is due to the strict relation to player's position and camera's position. This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing!

How can I solve this? How can I edit my RepositionCamera() to be less strict about moving itself?


I solved by doing this:

   player_camera_.Position = new Vector2(
            MathHelper.Lerp(player_camera_.Position.X, player_.Position.X - 250, 0.08f),
            MathHelper.Lerp(player_camera_.Position.Y, player_.Position.Y - 100y, 0.08f));

The reason the camera shakes is most likely because of it is not being repositioned at the right time, so it lags behind one frame.


HandleInput() - right
UpdatePlayer() - move to right
Draw() - player after moving to right
RepositionCamera() - set camera to player position.

The world had already been rendered when RepositionCamera is called, and the player is always ahead of the camera. It could be the way around also.

I'd suggest you fix that first, but here's an example of moving the camera smoothly:

Vector2 delta = player_.Position - current_camera.Position; //Distance from player to cam
current_camera.Position += delta * 0.1 //Move the camera by 10%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy