In Play class I have the viewport of game height=320 and game width=240unitswith camera cam. I have set the camera(cam) viewport width to 10 and viewport height to 7.I have another camera hud whose viewport width is game width and viewport height is game height. In render method, I have set Spritebatch to a projection matrix of hud.combined.Here is how the game looks likeGame

I want the camera to follow the player. I have tried this


After doing this, the tilemap is bouncing and i can see the black portion of the screen game after camera position set


2 Answers 2


Looking at it, you probably want to update only the x position of the camera. And since the player is not really centered, you may want to add a delta to it:

cam.position.x = player.getPosition().x + delta;           // adjust delta to your needs (start with 0, then increase it untill you find the right amount)
cam.update();                                              // don't forget to update

delta is the horizontal distance from the center of the screen to your player.

Note: This could use some lerping so that the camera movement is smooth:

cam.position.x += (player.getPosition().x + delta - cam.position.x) * lerp * deltaTime;

lerp should have a value between 0 and 1. Play around with it untill you get something good.

  • \$\begingroup\$ how to get delta by code? \$\endgroup\$
    – satya
    Jul 19, 2018 at 22:31
  • \$\begingroup\$ @satya actually you should provide delta. It's how far from the center the player is. You don't need to set the player position on start, just provide that delta and let the camera do the rest. \$\endgroup\$ Jul 19, 2018 at 22:45
  • \$\begingroup\$ I dont get it...how do I calculate the horizontal distance from the centre? \$\endgroup\$
    – satya
    Jul 20, 2018 at 1:17

After you set the position on the camera using cam.position call cam.update() to recalculate the matrices before you use combined.

  • \$\begingroup\$ I did that,The entire map moves up and down and i can see the black portion of the screen \$\endgroup\$
    – satya
    Jul 18, 2018 at 19:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .