Assets/Scripts/Utility/CameraAspect.cs (view raw)
1using System.Collections;
2using System.Collections.Generic;
3using UnityEngine;
4
5public class CameraAspect : MonoBehaviour
6{
7
8 // Use this for initialization
9 void Start()
10 {
11 // set the desired aspect ratio (the values in this example are
12 // hard-coded for 16:9, but you could make them into public
13 // variables instead so you can set them at design time)
14 float targetaspect = 16.0f / 9.0f;
15
16 // determine the game window's current aspect ratio
17 float windowaspect = (float)Screen.width / (float)Screen.height;
18
19 // current viewport height should be scaled by this amount
20 float scaleheight = windowaspect / targetaspect;
21
22 // obtain camera component so we can modify its viewport
23 Camera camera = GetComponent<Camera>();
24
25 // if scaled height is less than current height, add letterbox
26 if (scaleheight < 1.0f)
27 {
28 Rect rect = camera.rect;
29
30 rect.width = 1.0f;
31 rect.height = scaleheight;
32 rect.x = 0;
33 rect.y = (1.0f - scaleheight) / 2.0f;
34
35 camera.rect = rect;
36 }
37 else // add pillarbox
38 {
39 float scalewidth = 1.0f / scaleheight;
40
41 Rect rect = camera.rect;
42
43 rect.width = scalewidth;
44 rect.height = 1.0f;
45 rect.x = (1.0f - scalewidth) / 2.0f;
46 rect.y = 0;
47
48 camera.rect = rect;
49 }
50 }
51
52
53}