2
\$\begingroup\$

I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom = x) the camera is shifted when the player moves (the camera follows the player):

Shifted Position Shifted View

Normal Position Normal View

That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves.

Here's some of my code:

Render Loop (excerpt):

@Override
public void render(float delta) {
    //set the camera position to player's position
    cam.position.set(player_body.getWorldCenter().x, player_body.getWorldCenter().y, 0);
    cam.update();

    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    world.clearForces();

    handleInput();

    Gdx.gl.glClearColor(.05f, .05f, .05f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(cam.combined);

    debugRenderer.render(world, cam.combined);

}

Make the player move:

if (Gdx.input.isKeyPressed(Keys.W)) {
    player_body.setLinearVelocity(transX, transY);
    player.setMoving(true);
}
\$\endgroup\$
1
\$\begingroup\$

Okay, I found an answer. You need to set the camera's position directly after calling world.step() and then it works without shifting.

world.step(...);
camera.position.set(...);
camera.update();

(Original Answer)

\$\endgroup\$

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.