libgdxspriteprojectionspritebatch

Libgdx sprite not scalling with viewport


I have a stretch viewport that I update everytime the screen is rezised with:

viewport.update(x, y, true);

I drew a background with photoshop and then i removed the objects and put those in a separate file, so what i mean by this is that the objects are in the correct size from origin since i separated them from the original background and texturepacked them.

What i find is that if i draw this objects (using Sprite) i have to set the scale of each sprite to 2.25 otherwise the sprites would be smaller and I dont know what i am doing wrong since im using a single camera/viewport, a single batch and calling batch.setProjectionMatrix(camera.combined).

What i am doing wrong?

This is how i created the viewport and camera:

public static Dimension virtualResolution = VirtualResolution.RES_768x432.resolution;
public static Dimension screenResolution = new Dimension(1920, 1080); 

camera = new OrthographicCamera();
camera.setToOrtho(false, GameSettings.virtualResolution.getWidth(), GameSettings.virtualResolution.getHeight());
camera.update();

viewport = new StretchViewport(GameSettings.screenResolution.getWidth(), GameSettings.screenResolution.getHeight(), camera);
viewport.apply();

Solution

  • You are not using Cameras and Viewports correctly.

    Cameras have their own "view width" and "view height" which you actually specify in the setToOrtho method. However you don't need to set such things to a camera when you are using a Viewport.

    Instead you give these size parameters to the Viewport constructor along with an Orthographic camera.

    gamecam = new OrthographicCamera();
    gamePort = new StretchViewport(V_WIDTH, V_HEIGHT, gamecam);
    gamePort.apply();
    gamecam.position.set(new Vector3(100, 100, 0));
    

    In your game you will always work with the camera unless the screen is resized.

    If the screen is resized is the code will look like this.

    @Override public void resize(int width, int height) {
        gamePort.update(width, height); // The third boolean parameter
                                        // centers the camera
    }
    

    In your question you used two sizes, one based off of the screen resolution, the other a virtual width and height. You will only use one and this gets passed to the Viewport.

    This should now correctly scale your sprites!

    I hope this answer helped! If you have any more questions please feel free to comment below!