Created
March 4, 2023 00:43
-
-
Save sravankaruturi/c16c349bc1aec92461de362d5f95acf6 to your computer and use it in GitHub Desktop.
A small script to control the letterboxing in Unity. Attached to the main camera
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
public class PortraitLetterboxCamera : MonoBehaviour { | |
private Camera camera; | |
[SerializeField] | |
private bool allowOrthographicSizeChange; | |
[SerializeField] | |
private float cameraOrthographicSize; | |
// The Vertical Padding | |
[SerializeField] | |
private vec2 padding; | |
private void Awake() { | |
camera = GetComponent<Camera>(); | |
PerformViewportSizing(padding); | |
} | |
private void PerformViewportSizing(padding) { | |
var padding = padding | |
// Target Aspect Ratio | |
float targetRatio = (float)Screen.width / (Screen.height - (padding.x + padding.y)); | |
// Current Aspect Ratio | |
float currentRatio = (float)Screen.width / (float)Screen.height; | |
// Ratio Between them | |
float scaleheight = currentRatio / targetRatio; | |
Rect rect = camera.rect; | |
if (scaleheight < 1.0f) { | |
rect.width = 1.0f; | |
rect.height = scaleheight; | |
rect.x = 0; | |
rect.y = (padding.y / (float)Screen.height); | |
} else { | |
float scalewidth = 1.0f / scaleheight; | |
rect.width = scalewidth; | |
rect.height = 1.0f; | |
rect.x = (1.0f - scalewidth) / 2.0f; | |
rect.y = 0; | |
} | |
camera.rect = rect; | |
if (allowOrthographicSizeChange) { | |
camera.orthographicSize = cameraOrthographicSize; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment