首页 > 解决方案 > 用于不同纵横比的 Unity3D 画布缩放器

问题描述

在 Unity 中,我正在尝试为 android 和 ios 平台构建手机游戏。在发布游戏之前,我一直在尝试一些不同的屏幕分辨率以进行测试。我已经使用代码解决了解决问题,

[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
public class ControllingCameraAspectScript : MonoBehaviour
{
    public float sceneWidth = 21f;
    float targetaspect = 16.0f / 9.0f;
    float windowaspect = (float)Screen.width / (float)Screen.height;
    Camera camera;
    public Vector2 targetAspect = new Vector2(16, 9);
    
    void Start()
    {
        camera = GetComponent<Camera>();
        UpdateCrop();
    }

    public void UpdateCrop()
    {
        // Determine ratios of screen/window & target, respectively.
        float screenRatio = Screen.width / (float)Screen.height;
        float targetRatio = targetAspect.x / targetAspect.y;

        if (Mathf.Approximately(screenRatio, targetRatio))
        {
            // Screen or window is the target aspect ratio: use the whole area.
            camera.rect = new Rect(0, 0, 1, 1);
        }
        else if (screenRatio > targetRatio)
        {
            // Screen or window is wider than the target: pillarbox.
            float normalizedWidth = targetRatio / screenRatio;
            float barThickness = (1f - normalizedWidth) / 2f;
            camera.rect = new Rect(barThickness, 0, normalizedWidth, 1);
        }
        else
        {
            // Screen or window is narrower than the target: letterbox.
            float normalizedHeight = screenRatio / targetRatio;
            float barThickness = (1f - normalizedHeight) / 2f;
            camera.rect = new Rect(0, barThickness, 1, normalizedHeight);
        }
    }
}

此代码适用于低于 2.0 的纵横比。(16/9、16/10、5/4 等)。当涉及到 3200x1440 等屏幕分辨率时,即使关卡似乎被精细切割以匹配视图,画布也确实从屏幕上掉下来,如下面的屏幕截图所示。

纵横比:16/9(1280x768 的结果相同) 在此处输入图像描述

屏幕分辨率 3200x1440(纵横比高于 2.0) 在此处输入图像描述

画布设置

在此处输入图像描述

有人对这里的问题有想法吗?任何建议将不胜感激。

标签: unity3dscreen-resolution

解决方案


我已经为这个特定问题找到了一个很好的解决方案。

Letterboxer 可以轻松地自动将信箱、柱箱或像素完美的视图缩放添加到该游戏摄像机的视图。它还在编辑模式下进行更新,以在游戏视图中提供信箱的实时预览。

用法 -

  1. 将 Letterboxer 组件添加到您的 Camera GameObject。如果 GameObject 上不存在 Camera 组件,则会添加一个。

  2. 更改目标宽度和目标高度选项以满足您的需要。这些将用于确定“保持纵横比”模式的纵横比或“最佳像素完美匹配”模式的基本尺寸。

  3. 设置 Type 选项,这两个选项将在下面更详细地描述。

下载 - https://github.com/RyanNielson/Letterboxer


推荐阅读