0
\$\begingroup\$

I have a basic screen with 3 TextureRegions rendered on the screen rendered with this code(Ignore the hardcoded numbers, bad decision I know will be replaced later):

Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 225);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 150);
batch.draw(btnIdle, (Gdx.graphics.getWidth() / 2) - (169 / 2), 75);
batch.end();

and it renders like this:

enter image description here

But if I resize the window it becomes like this:

enter image description here

Why does the texture become like that when the window is resized and what are the solutions?

P.S. I am aware of this question and it does not solve my problem

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Figured it out, To actually get the resizing correctly a camera needs to be created:

OrthographicCamera camera;

and initialised in the create method:

camera = new OrthographicCamera(800, 480);
camera.position.set(800 / 2, 480 / 2, 0);

Then in the rendering method:

Set the projection matrix:

batch.setProjectionMatrix(camera.combined);

And update the camera:

camera.update();

And finally add this method:

@Override
public void resize(int width, int height) {
    camera.viewportWidth = width;
    camera.viewportHeight = height;
}

Entire source code:

SpriteBatch batch;

OrthographicCamera camera;

Texture menu;

TextureRegion btnIdle;

@Override
public void create () {
    camera = new OrthographicCamera(800, 480);
    camera.position.set(800 / 2, 480 / 2, 0);
    batch = new SpriteBatch();
    menu = new Texture("menuSprite.png");
    btnIdle = new TextureRegion(menu, 831, 228, 169, 32);
}

@Override
public void render () {
    batch.setProjectionMatrix(camera.combined);
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    batch.begin();
    batch.draw(btnIdle, camera.position.x - btnIdle.getRegionWidth() / 2, 225);
    batch.end();
}

@Override
public void resize(int width, int height) {
    camera.viewportWidth = width;
    camera.viewportHeight = height;
}
\$\endgroup\$

You must log in to answer this question.

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