Skip to content

Instantly share code, notes, and snippets.

@sravankaruturi
Created March 4, 2023 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sravankaruturi/c16c349bc1aec92461de362d5f95acf6 to your computer and use it in GitHub Desktop.
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
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