CapersProject/Assets/02.Scripts/BlueWater/AspectRatioController.cs
2025-02-10 11:13:46 +09:00

90 lines
2.5 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace DDD
{
public class AspectRatioController : MonoBehaviour
{
[SerializeField]
private List<Camera> _cameras = new();
[SerializeField]
private List<RectTransform> _canvasRectTransforms = new();
private float _targetAspect = 16f / 9f;
private void OnPreCull()
{
GL.Clear(true, true, Color.black);
}
private void Awake()
{
_canvasRectTransforms.Add(SceneController.Instance.Panel.GetComponent<RectTransform>());
EventManager.OnChangedDisplay += ChangeResolution;
}
private void OnDestroy()
{
EventManager.OnChangedDisplay -= ChangeResolution;
}
private float GetScaleHeight()
{
return ((float)Screen.width / Screen.height) / _targetAspect;
}
private void SetCamera()
{
foreach (var element in _cameras)
{
Rect cameraRect = element.rect;
float scaleHeight = GetScaleHeight();
float scaleWidth = 1f / scaleHeight;
if (scaleHeight < 1f)
{
cameraRect.height = scaleHeight;
cameraRect.y = (1f - scaleHeight) / 2f;
}
else
{
cameraRect.width = scaleWidth;
cameraRect.x = (1f - scaleWidth) / 2f;
}
element.rect = cameraRect;
}
}
private void AdjustUI()
{
float scaleHeight = GetScaleHeight();
foreach (var element in _canvasRectTransforms)
{
if (scaleHeight < 1f)
{
element.anchorMin = new Vector2(0f, (1f - scaleHeight) / 2f);
element.anchorMax = new Vector2(1f, 1f - (1f - scaleHeight) / 2f);
}
else
{
float scaleWidth = 1f / scaleHeight;
element.anchorMin = new Vector2((1f - scaleWidth) / 2f, 0f);
element.anchorMax = new Vector2(1f - (1f - scaleWidth) / 2f, 1f);
}
element.offsetMin = Vector2.zero;
element.offsetMax = Vector2.zero;
}
}
public void ChangeResolution()
{
AdjustUI();
SetCamera();
}
}
}