Created
August 31, 2018 01:37
-
-
Save codehoose/fd4facf7ed7d7f8b546c0933784f42e8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
/// <summary> | |
/// Aspect ratio controller. Must be attached to the main camera. | |
/// </summary> | |
[RequireComponent(typeof(Camera))] | |
public class AspectRatio : MonoBehaviour | |
{ | |
[Tooltip("The idea ratio that you want the world rendered at")] | |
public float perfectRatio = 16f / 9f; | |
private void Start() | |
{ | |
// Grab the camera component from the game object | |
var camera = GetComponent<Camera>(); | |
// Calculate the actual screen ratio | |
float aspectRatio = Screen.width / (float)Screen.height; | |
// Early out if the aspect ratio matches the perfect ratio | |
if (Mathf.Abs(aspectRatio - perfectRatio) < float.Epsilon) | |
return; | |
// Calculate the viewport height based on the current height and the perfect ratio | |
var viewportHeight = (Screen.width / perfectRatio) / Screen.height; | |
// Calculate the top-most position for the viewport | |
var yPos = (1f - viewportHeight) / 2f; | |
// Set the viewport | |
camera.rect = new Rect(0, yPos, 1f, viewportHeight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment