SamsonGame/Assets/Scripts/Game/Camera/CameraFovCorrector.cs

45 lines
1.5 KiB
C#
Raw Permalink Normal View History

2021-12-29 20:50:11 +03:00
using Cinemachine;
using RND;
using UnityEngine;
public class CameraFovCorrector : BaseCameraCorrector
{
private FovCorrector _data;
protected override void OnInit()
{
_data = new FovCorrector(VirtualCamera, VirtualCamera.m_Lens.FieldOfView);
}
public override void SyncCameraProperty(float widthOrHeight)
{
_data.SyncCameraFov(DefaultRatio, Camera.aspect, widthOrHeight);
}
private static float CalculateVerticalFov(float hFovInDeg, float aspectRatio)
{
float hFovInRads = hFovInDeg * Mathf.Deg2Rad;
float vFovInRads = 2 * Mathf.Atan(Mathf.Tan(hFovInRads / 2) / aspectRatio);
return vFovInRads * Mathf.Rad2Deg;
}
private class FovCorrector
{
private readonly float _defaultFov;
private readonly CinemachineVirtualCamera _virtualCamera;
public FovCorrector(CinemachineVirtualCamera camera, float defaultFov)
{
_virtualCamera = camera;
_defaultFov = defaultFov;
}
public void SyncCameraFov(float targetAspect, float cameraAspect, float widthOrHeight)
{
float horizontalFov = CalculateVerticalFov(_defaultFov, 1 / targetAspect);
float constantWidthFov = CalculateVerticalFov(horizontalFov, cameraAspect);
_virtualCamera.m_Lens.FieldOfView = Mathf.Lerp(constantWidthFov, _defaultFov, widthOrHeight);
}
}
}