KaiClavier

AspectUtility.cs

Jun 20th, 2022 (edited)
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.18 KB | None | 0 0
  1. /*
  2. This code is a modified and trimmed-down version of the code from
  3. http://wiki.unity3d.com/index.php?title=AspectRatioEnforcer
  4. and was originally written by Eric Haines.
  5.  
  6. It is only intended for demonstration purposes, and the full code is available for free online.
  7. ...Is what this originally said. The linked website went down, so I'm reuploading this for preservation purposes.
  8. */
  9. using UnityEngine;
  10.  
  11. public class AspectUtility : MonoBehaviour {
  12.     public float _wantedAspectRatio = 1.7777778f;
  13.     public Camera cam;
  14.  
  15.     public void Reset() {
  16.         cam = GetComponent<Camera>();
  17.     }
  18.  
  19.     public void SetCamera () {
  20.         float currentAspectRatio = (float)Screen.width / Screen.height;
  21.         if ((int)(currentAspectRatio * 100) / 100.0f == (int)(_wantedAspectRatio * 100) / 100.0f) {
  22.             cam.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  23.             return;
  24.         }
  25.         // Pillarbox
  26.         if (currentAspectRatio > _wantedAspectRatio) {
  27.             float inset = 1.0f - _wantedAspectRatio/currentAspectRatio;
  28.             cam.rect = new Rect(inset/2, 0.0f, 1.0f-inset, 1.0f);
  29.         }
  30.         // Letterbox
  31.         else {
  32.             float inset = 1.0f - currentAspectRatio/_wantedAspectRatio;
  33.             cam.rect = new Rect(0.0f, inset/2, 1.0f, 1.0f-inset);
  34.         }
  35.     }
  36. }
Add Comment
Please, Sign In to add comment