Files
bansonic_beta_main/Assets/CameraLetterBox.cs
2026-07-22 05:35:53 +08:00

67 lines
1.6 KiB
C#

using UnityEngine;
[ExecuteAlways]
[RequireComponent(typeof(Camera))]
public class CameraLetterbox : MonoBehaviour
{
public float targetAspect = 16f / 9f;
// 关闭时相机填满整个屏幕(跟随用户分辨率,无黑边);开启时回退到旧的 16:9 锁定加黑边行为。
// 透视相机填满屏幕会按 Hor+ 水平扩展视野,不会拉伸变形。
public bool lockAspect = false;
private int lastWidth;
private int lastHeight;
void OnEnable()
{
ApplyLetterbox();
lastWidth = Screen.width;
lastHeight = Screen.height;
}
void Update()
{
if (Screen.width != lastWidth || Screen.height != lastHeight)
{
ApplyLetterbox();
lastWidth = Screen.width;
lastHeight = Screen.height;
}
}
void ApplyLetterbox()
{
Camera cam = GetComponent<Camera>();
if (!lockAspect)
{
cam.rect = new Rect(0f, 0f, 1f, 1f);
return;
}
float screenAspect = (float)Screen.width / Screen.height;
float scaleHeight = screenAspect / targetAspect;
if (scaleHeight < 1.0f)
{
cam.rect = new Rect(
0,
(1f - scaleHeight) / 2f,
1,
scaleHeight
);
}
else
{
float scaleWidth = 1f / scaleHeight;
cam.rect = new Rect(
(1f - scaleWidth) / 2f,
0,
scaleWidth,
1
);
}
}
}