unity-game-engine2dorthographic

Camera orthographic size certain width


How do we can set a certain size of units for defining the width of the Orthographic size of the camera in the portrait mode?

I want to set the horizontal dimension to the 5 meters exactly from the center-left to the center-right of the screen for any mobile device? how can I achieve this? I've found this piece of code from a video clip but I don't understand it and I think it does not help me since I don't have a game field and also my game world will be generated automatically during the game (it's an infinite 2D scrolling game).

[SerializeField] private SpriteRenderer gameField;
void Start()
{
    float screenRatio = (float)Screen.width / (float)Screen.height;
    float targetRatio = gameField.bounds.size.x / gameField.bounds.size.y;
   
    if (screenRatio > targetRatio)
    {
        Camera.main.orthographicSize = gameField.bounds.size.y / 2;
    }
    else
    {
        float differenceInSize = targetRatio / screenRatio;
        Camera.main.orthographicSize = gameField.bounds.size.y / 2 * differenceInSize;
    }
}

I don't know why unity doesn't handle these issues automatically?


Solution

  • I have found the video you have been talking about and it is actually pretty simple. For reference, it is this video. I will try to explain it to you.
    These 5 boxes represent all content that you want to show on your screen. You want your camera to always adjust itself so it fits all of those boxes inside of it.

    enter image description here

    To archive this you have to multiply the width of our boxes (all of our boxes are 1 meter wide in all dimensions) by the screen height devided by the screen width. You then want to divide that number by two.

    boxes.width * screen.height / screen.width * 0.5
    

    In our code it looks like this:

    public float sizeInMeters;
    
    void Start()
    {
        float orthoSize = sizeInMeters * Screen.height / Screen.width * 0.5f;
    
        Camera.main.orthographicSize = orthoSize;
    }
    

    If you want to have five meters to the left and right from the middle then put in 10 into the sizeInMeters variable. If your total screen width from left to right should only cover 5 meters you have to put in 5 into the sizeInMeters variable. The if inside of your code is only there if you want the user to be able to flip his phone into a vertical position.

    enter image description here

    enter image description here