Skip to content Skip to sidebar Skip to footer

Camera Does Not Follow Player

I use libgdx have one player which moves in x direction from left to right. Now I want the camera to follow it (like in Flappy Bird for example). What happen is that the player

Solution 1:

try to use stage's camera instead of creating your own. Change your GameScreen constructor like this:

publicGameScreen(Game game){
        stage = newStage(newFitViewport(Game.WIDTH, Game.HEIGHT));
        camera = (OrthographicCamera) stage.getCamera();

        Gdx.input.setInputProcessor(stage);
    }

then in the render method set the camera position just like

    camera.position.set(player.getX(), camera.position.y, 0);

before camera.update() call


There is also something strange in your code - why you have camera.position.set() and setting player x in this condition:

    if (delta > 1 / 60f) //??
    {
        player.setX(player.getX() + (4 * delta));
        camera.position.set(player.getX(), camera.position.y, 0);
    }

I'm pretty sure you don't need this - but even if you need the

    camera.position.set(player.getX(), camera.position.y, 0);

should be out of if statement because what is happening now is that even if you are changing your player position (using keybord through PlayerInputHandler object) you **don't update camera position. Try to remove if statement or at least do something like

    public void render(float delta) 
    {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (delta > 1 / 60f) 
        {
            player.setX(player.getX() + (100 * delta));
        }

        camera.position.set(player.getX(), camera.position.y, 0);
        update();

        stage.act(delta);
        stage.draw();
    }

last thing is that if your stage is empty (excluding player) when camera will start to follow player - you will see as player not moving at all :) Add someting more to stage

Post a Comment for "Camera Does Not Follow Player"