Search code examples
c#unity-game-engine2dscreen-resolution

Unity: How to resize a whole 2D sprite scene to any screen resolution?


guys! We are developing a 2D game for desktop and mobile. It is grid-based although we decided not to use tilemaps and, instead, create our own grid by code, because we need to program different actions and interactions for each tile. The game UI is on a canvas and that part resizes as we expected. Also, everything already works quite well "functionality-wise" on both, mobile and desktop. The problem is that, as we made the main grid and objects as sprites, it works great on any 16:9 screen, but some of the screen space gets cut when it runs on any wider screen.

How can we resize the whole sprite scene depending on screen size? I guess it has more to do with the camera than with the actual objects but we don´t have a clear clue. We already looked into "pixel-perfect camera" and, although we haven´t dug too deeply into it, it looks like it´s aimed more towards preserving artwork at full resolution and not so much at what we need.

This one is from the PC where we are developing the game and where it looks as it should:enter image description here

And this one is from a PC with a wider screen (16:10) where the scene gets cropped from the sides (In the previous picture I marked in orange/yellow the columns that are lost in this one) enter image description here

I guess there should be a way to stretch all sprites to fit the screen, but I think the best way to go would be to get empty horizontal or vertical bars, on top and bottom or to the sides, in order to preserve the exact proportions, and that would be good enough. But how to do it?

Thanks in advance.


Solution

  • Solved! Starting with the great ideas ephb gave me, I finally decided to get a reference percentage between the screen width and height. So, for 1920x1080, which is the resolution I know the game looks correct in, I did a rule of three and got that 1080 is 56.25% of the screen width, and, that in that case, the camera size should be 5.

    Knowing those two elements, now I can check the height proportion for the user´s device and, using another rule of three, calculate the correct camera size, like this:

    Camera cam;
    void Awake()
    {
        cam = Camera.main;
        cam.orthographicSize = GetHeightProportion() * 5 / 56.25f; //1920x1080 reference ---
    }
    
    float GetHeightProportion()
    {
        return ((float)Screen.height * 100) / (float)Screen.width;
    }