3
\$\begingroup\$

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

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 game after camera position set

\$\endgroup\$
2
\$\begingroup\$

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.

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

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

\$\endgroup\$
  • \$\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 '18 at 19:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.