Skip to content

ViewportWidget

raeleus edited this page Sep 5, 2021 · 3 revisions

ViewportWidget

The ViewportWidget allows you to embed an entire viewport within your UI. This is an excellent tool to integrate your games into a UI instead of just overlaying the UI on top of it. Use layout controls to dynamically position and resize your viewport or apply Actions for fun effects.

How to use ViewportWidget

ViewportWidget is a very simple class. You will be using two Viewports: one for your game (or whatever you are rendering) and one for your UI:

stage = new Stage(new ScreenViewport());
gameViewport = new StretchViewport(800, 800);

You can employ any kind of Viewport you desire for either one. Create a ViewportWidget then add it to your layout:

ViewportWidget viewportWidget = new ViewportWidget(gameViewport);
table.add(viewportWidget);

Ensure that you are rendering the viewports in the order that you intend. You won't be able to see your game if it's completely obscured by your UI and vice versa. It is not rendered in the depth specified by Scene2D. Follow the typical instructions to render your game and switch between ViewPorts:

//Conduct your game logic and make sure the stage is updated before the viewports are drawn
stage.act();

stage.getViewport().apply();
stage.draw();

//pass a "true" if you want to center the camera
gameViewport.apply(true);
spriteBatch.setProjectionMatrix(gameViewport.getCamera().combined);
TextureRegion textureRegion = skin.getRegion("island");
spriteBatch.begin();
//draw your game here
spriteBatch.draw(textureRegion, 0, 0);
spriteBatch.end();

image

See the ViewportWidgetTest for a resizable example.

Clone this wiki locally