How do I make the camera follow the player in LibGDX

user3798172 picture user3798172 · Jul 2, 2014 · Viewed 11.6k times · Source

I've been following the "How to make a 2D game" here, but it wasn't shown how make a camera follow a specific sprite.

My rendering code is as follows

public class [ClassName] {
    polkymain game; 
    OrthographicCamera camera;

    public static int PolkyX;
    public static int PolkyY;

    SpriteBatch batch;

    public GameScreen(polkymain game) {
        this.game = game;
    
        camera = new OrthographicCamera();
        camera.setToOrtho(true, 1280, 1240);
    
        batch = new SpriteBatch();
    
        PolkyX = 0;
        PolkyY = 0;     
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0.95F, 0.95F, 0.95F, 0.95F);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);       
    
        camera.update();
        generalUpdate();
    
        batch.setProjectionMatrix(camera.combined);     
        batch.begin();          
        batch.draw(Assets.Sprite_Mario_main, PolkyX, PolkyY);       
        batch.end();
    }

    public void generalUpdate(){
        if(Gdx.input.isKeyPressed(Keys.D) || (Gdx.input.isKeyPressed(Keys.LEFT))
        {
            PolkyX += 5;
        }
    
        if(Gdx.input.isKeyPressed(keys.A) || (Gdx.input.isKeyPressd(Keys.RIGHT))
        {
            PolkyX -= 5;
        }

        if(Gdx.input.isKeyPressed(keys.S) || (Gdx.input.isKeyPressd(Keys.DOWN))
        {
            PolkyY -= 5;
        }

        if(Gdx.input.isKeyPressed(keys.W) || (Gdx.input.isKeyPressd(Keys.UP))
        {
            PolkyY += 5;
        }       
    }

    @Override
    public void resize(int width, int height) { /* TODO */ }

    @Override
    public void show() {  /* TODO */ }

    @Override
    public void hide() { /* TODO */ }

    @Override
    public void pause() { /* TODO */ }

    @Override
    public void resume() { /* TODO */ }

    @Override
    public void dispose() { /* TODO */ }
}

Also, I have an "Assets" class with all my textures and sprites coding, don't know if this is relevant. I don't think so now that I think about it.

Answer

clearlyspam23 picture clearlyspam23 · Jul 2, 2014

The easiest way to get the camera to follow is to simply set its location to the center of your sprite every render call, like so:

//move your sprite
camera.position.set(sprite.getX(), sprite.getY(), 0);
camera.update();
//draw everything

This will make the camera exactly match the location of the sprite each iteration. If you want some smoother/more complex following, you should look into some form of interpolation (more info can be found here).