I use Box2D to manage my game world. I want to display text above the body. I plan to do this by setting the Label appropriately. The problem is that the body is in the game world and the Label is in the Stage (UI). So I tried to use the camera.project() method to convert world coordinates to screen coordinates. Unfortunately, for some reason I couldn't do it - the Label is displayed in a different place than it should be - it is shifted down and to the left relative to the target position. When resizing the window, this position also changes, but also incorrectly. I will add that otherwise I use the camera.unproject() method in the same way and I have no problems here - everything works fine. I don't know why it's different the other way around.
this.camera = new OrthographicCamera(ScreenManager.WIDTH * SCALE, ScreenManager.HEIGHT * SCALE);
this.viewport = new FitViewport(ScreenManager.WIDTH, ScreenManager.HEIGHT);
this.stage = new Stage(viewport, batch);
this.world = new World(Vector2.Zero, true);
// ...
Vector3 worldPosition = new Vector3(x, y, 0);
Vector3 screenPosition = camera.project(worldPosition,
viewport.getScreenX(), viewport.getScreenY(),
viewport.getScreenWidth(), viewport.getScreenHeight());
label.setPosition(screenPosition.x, screenPosition.y);
And my resize method:
@Override
public void resize(int width, int height) {
viewport.update(width, height, true);
}
Of course I call act() and draw() for Stage in the render method. What am I doing wrong?
In order to translate from
World-coordinates toStage-coordinates you need to first project theWorldposition onto screen-space, and then unproject it back intoStage-space.That process will allow you to track a Box2D
Bodyand set aLabels position to match it:Full source for the example above is included below, it uses the default font from the libGDX tests (font and the font image).