1
votes

I would like to have two SpriteBatch objects, one for the actual sprites and one for a HUD. I can't figure out how to make one SpriteBatch stay relative to the screen but to have the other move around, centered on the player's Body. I have one OrthographicCamera for box2d Bodies and one for the sprites.

I thought that the setProjectionMatrix method would solve this, but I might be using it wrong.

In the main file:

public void render () {
        stateManager.getActiveState().update(Gdx.graphics.getDeltaTime());
        spriteBatch.setProjectionMatrix(camera.combined);
        spriteBatch.begin();
        stateManager.getActiveState().render(spriteBatch);
        spriteBatch.end();
        debugRenderer.render(world, b2dCamera.combined);
    }

stateManager.getActiveState().update(Gdx.graphics.getDeltaTime()); calls:

public void update(float dt) {
        this.player.update(dt);
        this.camera.position.set(this.player.getCenter().x * Game.getPpm(), this.player.getCenter().y * Game.getPpm(), 0);
        this.b2dCamera.position.set(this.player.getCenter().x, this.player.getCenter().y, 0);
        this.camera.update();
        this.b2dCamera.update();
        this.joystick.update();
    }

stateManager.getActiveState().render(spriteBatch); calls:

public void render(SpriteBatch spriteBatch) {
        this.playBatch.begin();
        System.out.println(playBatch.getProjectionMatrix());
        System.out.println(spriteBatch.getProjectionMatrix());
        font.draw(spriteBatch, "Hello", 0, 60);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        this.player.render(playBatch);
        this.joystick.render(spriteBatch);
        this.world.step(Gdx.graphics.getDeltaTime(), 8, 3);
        this.playBatch.end();
    }

This gives me "hello" that stays in the bottom left corner, a body that stays in the center and rotates (because the camera is centered to the center of the body, and my sprite (associated with the body) moves to the right while rotating in sync with the body.

I want the sprite to not move (to move in the world, but the camera should center on it like it does with the body) and be completely in sync with the body.

When I print the ProjectionMatrix of spriteBatch, it is the same in every iteration, but playBatch moves

image

UPDATE Nothing changes if I comment out spriteBatch.setProjectionMatrix(camera.combined); from the main file

This might not be the best way to have a game with a hud, so let me know if you have a better alternative. Thank you

1
Have you considered adding a separate camera/viewport for HUD instead of having two Batches? It should be much easier to manage. - warownia1

1 Answers

1
votes

I found the solution. I was having the begin and end of the two spriteBatches overlap, which cause weird things to happen. I am now calling begin ... end of one and begin ... end of the other.