Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Make a 2D camera always fill the biggest square?

Discussion in '2D' started by HaydarLion, Apr 4, 2017.

  1. HaydarLion

    HaydarLion

    Joined:
    Sep 17, 2014
    Posts:
    62
    Hey all,

    I am trying to get the main camera in my Unity project to always fill the biggest square it can in any resolution. That means it would have 2 equal pillar bars on a wider screen, but on a screen with a 1:1 ratio, it would fill the entire screen. How would I go about getting that effect?

    Thanks
     
  2. sngdan

    sngdan

    Joined:
    Feb 7, 2014
    Posts:
    1,131
    perspective or orthographic ?

    In general get min of screen width & height. Use this min to set orthographic size (1/2) or calculate distance of camera (considering field of view)
     
  3. HaydarLion

    HaydarLion

    Joined:
    Sep 17, 2014
    Posts:
    62
    It's an orthographic camera, and what I'm trying to achieve is that the game, when in fullscreen, always reaches from the top to the bottom of the screen, but still is a square with a 1:1 ratio, and to have any extra space on either side of the camera be a pillar bar.
     
  4. sngdan

    sngdan

    Joined:
    Feb 7, 2014
    Posts:
    1,131
    Untested but this should be in the right direction...you basically want to force a pillar box.

    EDIT: You would not want to run this in Update though in a real game setup. You can add Execute in Editor Mode to see in unity.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraScaler : MonoBehaviour {
    6.  
    7.     void Update ()
    8.     {
    9.      
    10.         float screenAspect = (float) Screen.width / Screen.height;
    11.         float adjustment;
    12.      
    13.         if (screenAspect > 1f)
    14.         {
    15.             adjustment = 1.0f - 1f/screenAspect;
    16.             Camera.main.rect = new Rect(adjustment/2f, 0.0f, 1.0f-adjustment, 1.0f);
    17.         }
    18.     }
    19. }