76 lines
2.7 KiB
C#
76 lines
2.7 KiB
C#
|
using Cinemachine;
|
|||
|
using UnityEngine;
|
|||
|
|
|||
|
public class CameraConstantWidth : MonoBehaviour
|
|||
|
{
|
|||
|
[SerializeField] private Vector2 _defaultResolution = new Vector2(360f, 640f);
|
|||
|
[Range(0f, 1f)] public float WidthOrHeight = 0;
|
|||
|
|
|||
|
public bool _debug;
|
|||
|
|
|||
|
private Camera componentCamera;
|
|||
|
|
|||
|
private float _initialSize;
|
|||
|
private float _targetAspect;
|
|||
|
|
|||
|
private float _initialFov;
|
|||
|
private float _horizontalFov = 120f;
|
|||
|
|
|||
|
private void Awake()
|
|||
|
{
|
|||
|
componentCamera = GetComponent<Camera>();
|
|||
|
_initialSize = componentCamera.orthographicSize;
|
|||
|
|
|||
|
_targetAspect = _defaultResolution.x / _defaultResolution.y;
|
|||
|
|
|||
|
_initialFov = componentCamera.fieldOfView + 20f; //80
|
|||
|
_horizontalFov = CalcVerticalFov(_initialFov, 1 / _targetAspect);
|
|||
|
}
|
|||
|
|
|||
|
private void OnEnable()
|
|||
|
{
|
|||
|
if (componentCamera.orthographic)
|
|||
|
{
|
|||
|
float constantWidthSize = _initialSize * (_targetAspect / componentCamera.aspect);
|
|||
|
componentCamera.orthographicSize = Mathf.Lerp(constantWidthSize, _initialSize, WidthOrHeight);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
float constantWidthFov = CalcVerticalFov(_horizontalFov, componentCamera.aspect);
|
|||
|
componentCamera.fieldOfView = Mathf.Lerp(constantWidthFov, _initialFov, WidthOrHeight);
|
|||
|
|
|||
|
CinemachineVirtualCamera[] camComp = transform.parent.GetComponentsInChildren<CinemachineVirtualCamera>(true);
|
|||
|
for (int i = 0; i < camComp.Length; i++)
|
|||
|
camComp[i].m_Lens.FieldOfView = Mathf.Lerp(constantWidthFov, _initialFov, WidthOrHeight);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private void Update()
|
|||
|
{
|
|||
|
if (_debug == false)
|
|||
|
return;
|
|||
|
|
|||
|
if (componentCamera.orthographic)
|
|||
|
{
|
|||
|
float constantWidthSize = _initialSize * (_targetAspect / componentCamera.aspect);
|
|||
|
componentCamera.orthographicSize = Mathf.Lerp(constantWidthSize, _initialSize, WidthOrHeight);
|
|||
|
}
|
|||
|
else
|
|||
|
{
|
|||
|
float constantWidthFov = CalcVerticalFov(_horizontalFov, componentCamera.aspect);
|
|||
|
componentCamera.fieldOfView = Mathf.Lerp(constantWidthFov, _initialFov, WidthOrHeight);
|
|||
|
|
|||
|
CinemachineVirtualCamera[] camComp = transform.parent.GetComponentsInChildren<CinemachineVirtualCamera>(true);
|
|||
|
for (int i = 0; i < camComp.Length; i++)
|
|||
|
camComp[i].m_Lens.FieldOfView = Mathf.Lerp(constantWidthFov, _initialFov, WidthOrHeight);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
private float CalcVerticalFov(float hFovInDeg, float aspectRatio)
|
|||
|
{
|
|||
|
float hFovInRads = hFovInDeg * Mathf.Deg2Rad;
|
|||
|
float vFovInRads = 2 * Mathf.Atan(Mathf.Tan(hFovInRads / 2) / aspectRatio);
|
|||
|
|
|||
|
return vFovInRads * Mathf.Rad2Deg;
|
|||
|
}
|
|||
|
}
|