Search code examples
cameralibgdxviewportscene2d

Multiple Stages on Same screen with different viewport LIBGDX


I am trying to scale my application to work similar on various aspect ratios.

I read about viewport and camera. And came to a conclusion that I should use FitViewport for my game stage so that no asset is being stretched. And I will use some background image to fill the black bars caused by fitviewport. But the problem is, whenever I use any other viewport than FitViewport for background image, the whole stage (both background and main stage) are being stretched, is there a way we can get away from black/white bar of FitViewport? I tried all the viewports for background namely StretchViewport, ScreenViewport, FillViewport.

Am I missing something very trivial? or is setting up multiple different viewport on same screen possible.

ps I was able to setup two same viewports with different size on same screen. Here is the screen, I am getting after fitviewport. Notice the white bars on top and bottom which I am trying to eliminate.

enter image description here


Solution

  • this answer worked for me. Just for reference

    You would need a second viewport, probably ExtendViewport with the same virtual dimensions as your FitViewport.

    //create:
    fitViewport = new FitViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    extendViewport = new ExtendViewport(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    
    //resize:
    fitViewport.update(width, height);
    extendViewport.update(width, height);
    
    //render:
    
    fitViewport.apply();
    batch.setProjectionMatrix(fitViewport.getCamera().combined);
    batch.begin();
    //draw game
    batch.end();
    
    extendViewport.apply();
    batch.setProjectionMatrix(extendViewport.getCamera().combined);
    batch.begin();
    //draw stuff in border
    batch.end();
    

    If you want to be sure the border stuff doesn't overlap your game, you could swap the draw order above.

    Or you could just use ExtendViewport to begin with for everything.