63 lines
2.2 KiB
C#
63 lines
2.2 KiB
C#
using UnityEngine;
|
|
|
|
/// <summary>
|
|
/// gameplay 世界空间背景(SpriteRenderer,如 bg_replace)自适应覆盖。
|
|
/// 该背景由透视相机渲染、带旋转/缩放,尺寸按 16:9 设计。超宽屏(21:9/32:9)下相机
|
|
/// 水平视野扩大会看到背景边缘之外的黑边,故按屏幕宽高比等比放大其 localScale 使其覆盖。
|
|
///
|
|
/// 仅调整 localScale(表现层),不改旋转/位置/材质/引用,不影响业务逻辑与动画。
|
|
/// 16:9 屏下缩放系数=1,与原设计逐像素一致。由 UIResolutionAutoFitter 自动附加。
|
|
///
|
|
/// 满足三要求:1) 不改业务逻辑/引用;2) 16:9 缩放=1、不动旋转位置;3) 超宽屏铺满。
|
|
/// </summary>
|
|
[RequireComponent(typeof(SpriteRenderer))]
|
|
[DisallowMultipleComponent]
|
|
public sealed class UISpriteBackgroundCover : MonoBehaviour
|
|
{
|
|
private const float DesignAspect = 16f / 9f;
|
|
|
|
private Transform tf;
|
|
private Vector3 baseScale; // 初始设计缩放(16:9 基准),永不变
|
|
private bool baseCaptured;
|
|
private int lastW = -1, lastH = -1;
|
|
|
|
private void OnEnable()
|
|
{
|
|
tf = transform;
|
|
CaptureBaseScale();
|
|
Apply();
|
|
}
|
|
|
|
private void CaptureBaseScale()
|
|
{
|
|
if (baseCaptured) return;
|
|
baseScale = tf.localScale;
|
|
baseCaptured = true;
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
if (Screen.width != lastW || Screen.height != lastH)
|
|
{
|
|
Apply();
|
|
}
|
|
}
|
|
|
|
private void Apply()
|
|
{
|
|
if (!baseCaptured) CaptureBaseScale();
|
|
lastW = Screen.width;
|
|
lastH = Screen.height;
|
|
|
|
float aspect = (float)Screen.width / Mathf.Max(1, Screen.height);
|
|
// 更宽的屏:水平视野变宽,需按 aspect/DesignAspect 放大以覆盖两侧。
|
|
// 更窄的屏:垂直视野相对更高,需按 DesignAspect/aspect 放大以覆盖上下。
|
|
// 取二者较大值(cover),保证任一方向都不露黑边。16:9 时系数=1。
|
|
float widthFactor = aspect > DesignAspect ? aspect / DesignAspect : 1f;
|
|
float heightFactor = aspect < DesignAspect ? DesignAspect / aspect : 1f;
|
|
float factor = Mathf.Max(widthFactor, heightFactor);
|
|
|
|
tf.localScale = baseScale * factor;
|
|
}
|
|
}
|