Skip to content
Advertisement

How to render something using screen coords and not world coords libgdx

I have some UI classes I made myself but I need a way to get them rendered on the Screen on one fixed place independent of the woorld and the camera moving. I just need it there. I am doing this in libgdx and I was wondering if theres a method that draws in relation to the screen coords and not the woorld coords because my camera moves around which causes the UI to fall out of view. I’ve tried to set the UI’s position relative to the camera so instead of rendering at x, y it renders at cam.position.x - n, cam.position.y - i but that didn’t work for some other reasons and isn’t really the optimal solution I seek for.

Advertisement

Answer

The easiest way to do this is to use two cameras – one for the world and one for the UI:

An example from one of my projects:

private void initializeCamerasAndViewports() {
    camera = new OrthographicCamera();
    // create a second camera and viewport for the UI
    cameraHud = new OrthographicCamera();
    viewport = new FitViewport(Constants.SCENE_WIDTH, Constants.SCENE_HEIGHT, camera);
    viewportHud = new FitViewport(Constants.SCENE_WIDTH * Constants.HUD_SCENE_FACTOR, Constants.SCENE_HEIGHT * Constants.HUD_SCENE_FACTOR,
            cameraHud);
    
    cameraHud.position.x = Constants.HUD_SCENE_WIDTH * 0.5f;
    cameraHud.position.y = Constants.HUD_SCENE_HEIGHT * 0.5f;
    
    camera.position.x = Constants.SCENE_WIDTH;
    camera.position.y = Constants.SCENE_HEIGHT;
    camera.zoom = 1.5f;
    
    cameraHud.update();
}

Then you can create a second SpriteBatch and use the UI camera to draw the UI that doesn’t move with the rest of the world:

private SpriteBatch uiBatch = new SpriteBatch();

public void render(float delta) {
    // ...
    uiBatch.setProjectionMatrix(cameraHud.combined);

    // TODO draw the UI using the new batch
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement