How to make the camera follow the player in Libgdx?

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 like

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

cam.position.set(player.getPosition().x,player.getPosition().y,0);


After doing this, the tilemap is bouncing and i can see the black portion of the screen

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;
cam.update();


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

• how to get delta by code? – satya Jul 19 '18 at 22:31
• @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. – ibrahim mahrir Jul 19 '18 at 22:45
• I dont get it...how do I calculate the horizontal distance from the centre? – satya Jul 20 '18 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.

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