Codixie

CameraConstantWidth

CameraConstantWidth

1using UnityEngine;
2
3public class CameraConstantWidth : MonoBehaviour
4{
5    [SerializeField] private Vector2 defaultResolution = new Vector2(1080, 1920);
6    [SerializeField] [Range(0f, 1f)] public float widthOrHeight = 0;
7
8    private Camera componentCamera;rew
9    private float initialSize;
10    private float targetAspect;
11    private float initialFov;
12    private float horizontalFov = 120f;
13
14    private void Start()
15    {
16        componentCamera = GetComponent<Camera>();
17        initialSize = componentCamera.orthographicSize;
18
19        targetAspect = defaultResolution.x / defaultResolution.y;
20
21        initialFov = componentCamera.fieldOfView;
22        horizontalFov = CalcVerticalFov(initialFov, 1 / targetAspect);
23    }
24
25    private void Update()
26    {
27        if (componentCamera.orthographic)
28        {
29            var constantWidthSize = initialSize * (targetAspect / componentCamera.aspect);
30            componentCamera.orthographicSize = Mathf.Lerp(constantWidthSize, initialSize, widthOrHeight);
31        }
32        else
33        {
34            var constantWidthFov = CalcVerticalFov(horizontalFov, componentCamera.aspect);
35            componentCamera.fieldOfView = Mathf.Lerp(constantWidthFov, initialFov, widthOrHeight);
36        }
37    }
38
39    private float CalcVerticalFov(float hFovInDeg, float aspectRatio)
40    {
41        var hFovInRads = hFovInDeg * Mathf.Deg2Rad;
42        var vFovInRads = 2 * Mathf.Atan(Mathf.Tan(hFovInRads / 2) / aspectRatio);
43        return vFovInRads * Mathf.Rad2Deg;
44    }
45}