0
\$\begingroup\$

I'm having an issue that I'm sure boils down to something simple that I've missed: The UI Graphics can't handle a window resize. Either the graphics get stretched, or the placement is incorrect.

For now I'm working with just one UI element consisting of a Sprite, until i've gotten the project to render properly. Its position is defined in a Settings-class when the asset is loaded:

    touchpadBG = new Sprite(assets.get("ui/joystick_background.png", Texture.class));
    touchpadBG.setCenter(Settings.touchpadPositionX, Settings.touchpadPositionY);

... and drawn like so:

batch.setProjectionMatrix(gameCam.combined);
batch.begin();
// Draw the gameworld. This is done without any issues.


batch.setProjectionMatrix(uiCam.combined);
touchpadBG.draw(batch);

batch.end();

uiCam is defined like this:

    this.uiCam = new OrthographicCamera(Settings.windowSize_X, Settings.windowSize_Y);
    uiCam.translate(Settings.windowSize_X / 2, Settings.windowSize_Y / 2, 0);
    uiCam.update();
    uiViewport = new FitViewport(Settings.windowSize_X, Settings.windowSize_Y, uiCam);
    uiViewport.apply();

I've experimented with different viewports (and no viewport), and while correct placement happens at first, resizing the window will result in the UI element being drawn in the wrong position, stretched, or both.

I then suspected my resize/update methods being off, but I can't find anything wrong:

public void resize(int w, int h) {
    uiViewport.update(w, h);
    update();
}

public void update() {
    aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
    uiCam.update();
    gameCam.update();
}

Any ideas where I'm going wrong with this? If my post is missing a relevant part of my code, leave a comment, and I'll edit it in.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Fixed it. For starters, I was using the wrong viewport. Changing uiViewport to a ScreenViewport fixed the scaling issue. Apart from that, I had overlooked the fact that I didn't apply() the new viewport after resizing.

uiCam and uiViewport is now created like this:

this.uiCam = new OrthographicCamera(Settings.windowSize_X, Settings.windowSize_Y);
uiCam.translate(Settings.windowSize_X / 2, Settings.windowSize_Y / 2, 0);
uiCam.update();
uiViewport = new ScreenViewport(uiCam);
uiViewport.apply();

Resize and update methods:

public void resize(int w, int h) {
    uiViewport.update(w, h, true);
    uiViewport.apply();
    update();
}    

public void update() {
    uiCam.update();
    gameCam.update();
}

Works like a charm: Touchpad stays in the correct position, and it's rever stretched.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Friendly reminder for picking an answer :) \$\endgroup\$ May 18, 2017 at 5:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .