Search code examples
camerascrollbox2dlibgdx

cameras in libgdx and box2d


I develop 2D game using libGDX and box2D. Camera is following with body.I want to scroll background (png 3200X48) too. Now the camera works fine in box2D world but background is not moving. I searched and tried many solutions but didn't help. What is the best solution for it? Maybe makes two cameras one for physics world and second for libgdx scene? Has someone got the similar problem? Thanks for help. Here are a parts of my code

    float w = 320;
    float h = 480;

        @Override
    public void show() {
            camera = new OrthographicCamera();
        camera.setToOrtho(false, w/2, h/2);
        world = new World(new Vector2(0, -20), true);
        box2DDebugRenderer = new Box2DDebugRenderer();
    background = new Texture(Gdx.files.internal("gfx/forklift/background.png"));
    bg = new Sprite(background);
    ......}
    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1f, 1f, 1f, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    moveCamera(dynamicBody.getPosition().x);
     moveBody();
        batch.begin();
        batch.draw(background, 0, 0, 3200, 480);
        batch.end();
    Gdx.app.log("", ""+dynamicBody.getPosition());
        world.step(1/60f, 6, 2);
        box2DDebugRenderer.render(world, camera.combined);}

    public void moveCamera(float x){
        camera.position.set(x, dynamicBody.getPosition().y, 0);
        camera.update();
        }
    @Override
    public void resize(int w, int h) {
    camera = new OrthographicCamera(w, h);
        camera.translate(h/2, w/2, 0);
        super.resize(w, h);
    }

Solution

  • use batch.setProjectionmatrix(camera.combined) before batch.begin()