blink.52
blink.52

Reputation: 1

Texture size with Libgdx

It may be a dumb question but I need a little help / explanations. I can't manage to resize correctly my textures when I resize the window in libgdx. I want to keep the aspect of my textures or have them at least reduced on a lower screen size, like on a mobile device. Here is a sample of my code, my original window size is 600*700 I tried a lot of things but nothing works :\

Can you help me ? Thanks in advance.

public class GameScreen implements Screen {

    private World world;
    private int ppxX, ppxY;
    private SpriteBatch batch;
    private OrthographicCamera camera;
    private float cameraX, cameraY;

    public GameScreen(World world) {
        this.world = world;
        camera = new OrthographicCamera();
    }

    public void show() {
        batch = new SpriteBatch();
    }

    @Override
    public void render(float delta) {
        world.update(delta);
        updateCamera();

        ppxX = Gdx.graphics.getWidth() / 600;
        ppxY = Gdx.graphics.getHeight() / 700;

        Gdx.gl.glClearColor(0f, 0f, 0f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        batch.draw(world.getTexture(), 0, 0, ppxX, ppxY);

        for (GameElement e : world.getListElements()) {
            e.update(delta);
            batch.draw(e.getTexture(), e.getPositionX()*ppxX, e.getPositionY()*ppxY, e.getWidth()*ppxX , e.getHeight()*ppxY );
        }

        batch.end();
    }

Upvotes: 0

Views: 2101

Answers (1)

yigiter
yigiter

Reputation: 412

You are on the right track, but there is couple of things you have to change.

  1. Use ViewPorts

    this.camera = new OrthographicCamera();
    this.viewport = new FitViewport(WORLD_SIZE_X, WORLD_SIZE_Y, this.camera);
    this.batch = new SpriteBatch();
    this.batch.setProjectionMatrix(this.camera.combined);
    
  2. Resize correctly.

    @Override
    public void resize(int width, int height) {
        this.viewport.update(width, height);
    }
    
  3. Update the camera and render using World Units. Do not make the mistake of thinking in Screen Pixels.

    public void render(float delta) {
        this.camera.update();
        this.batch.setProjectionMatrix(this.camera.combined);
    
        this.batch.begin();
    
        // draw using WORLD_SIZE
    
        this.batch.end();
    }
    

Upvotes: 2

Related Questions