I've been following some tutorials about libGdx and I've tried to create a 2d platformer but I've got stuck at how would be the right way to make the camera not go out of the screen when the player moves :(
The camera follows the player when it moves on the x coordinate position but if i go near where the map ends the camera will go out of the screen and i'm not sure how to solve that
Here is the main code of the game:
public PlayScreen(SuperShooter game){
this.game = game;
atlas = new TextureAtlas("Diz_Pack.atlas");
gamecam = new OrthographicCamera();
gamePort = new StretchViewport(SuperShooter.V_WIDTH / SuperShooter.PPM, SuperShooter.V_HEIGHT / SuperShooter.PPM, gamecam);
hud = new Hud(game.batch);
mapLoader = new TmxMapLoader();
map = mapLoader.load("Level1WithObjects2.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1/SuperShooter.PPM);
//initailly set our gamecam to be centered correctly at the start of
gamecam.position.set(gamePort.getWorldWidth()/2 , gamePort.getWorldHeight()/2, 0);
world = new World(new Vector2(0,-10), true);
new B2WorldCreator(world, map);
controller = new Controller(game);
// b2dr = new Box2DDebugRenderer();
player = new John(world, this);
world.setContactListener(new WorldContactListener());
}
public void update(float dt){
handleInput(dt);
world.step(1/60f, 6, 2); // in order for box2d to execute our physics simulation we need to tell it how many times to calculate per second
player.update(dt);
gamecam.position.x = player.b2body.getPosition().x;
gamecam.update();
renderer.setView(gamecam);
}
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
//render our Box2dDebugLines
//b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(gamecam.combined);
game.batch.begin();
player.draw(game.batch);
game.batch.end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined); //you have something that can draw to the screen via gpu like the spritebatch. And you have a camera.
//you gotta tell the spritebatch where we are / where the camera is looking, because on screen shall be what the camera is looking at.
hud.stage.draw();
controller.draw();
}
The camera is at first set on the left bottom of the screen but then, while the game updates it's placed on the x position of the player and that's why it looks like that:( do you guys know how should it be done to show only the map when the player moves? should i position the camera in front of the player or something like that?
Help would be appreciated! thanks