如何自动缩放到不同的屏幕分辨率?

时间:2014-08-06 02:50:35

标签: c# unity3d 2d resolution

我在团结中创造了一个无限的跑步者,我有一个瓦片生成器/生成器,它根据屏幕的高度和宽度生成GameObjects,我设法让它与宽度一起工作但是当改变高度时相机没有跟着,我无法做到这一点。

无论如何,我的代码不好,我花了最后6个小时,我不欣赏结果。

我发现你可以为相机定义宽高比,它会自动缩放你的比例,但它会使图像失真并且看起来不太好。

由于所有这些笔记,这是自动缩放2D平台游戏的最佳方式(不考虑GUI,只有GameObjects)

2 个答案:

答案 0 :(得分:1)

我'使用此脚本根据其大小拉伸精灵,适用于大多数情况。我使用5作为相机的orthographicSize。

using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
[ExecuteInEditMode]
#endif
public class SpriteStretch : MonoBehaviour {
    public enum Stretch{Horizontal, Vertical, Both};
    public Stretch stretchDirection = Stretch.Horizontal;
    public Vector2 offset = new Vector2(0f,0f);

    SpriteRenderer sprite;
    Transform _thisTransform;


    void Start () 
    {
        _thisTransform = transform;
        sprite = GetComponent<SpriteRenderer>();
        StartCoroutine("stretch");
    }
    #if UNITY_EDITOR
    void Update()
    {
        scale();
    }
    #endif
    IEnumerator stretch()
    {
        yield return new WaitForEndOfFrame();
        scale();
    }
    void scale()
    {
        float worldScreenHeight = Camera.main.orthographicSize *2f;
        float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
        float ratioScale = worldScreenWidth / sprite.sprite.bounds.size.x;
        ratioScale += offset.x;
        float h = worldScreenHeight /  sprite.sprite.bounds.size.y;
        h += offset.y;
        switch(stretchDirection)
        {
        case Stretch.Horizontal:
            _thisTransform.localScale = new Vector3(ratioScale,_thisTransform.localScale.y,_thisTransform.localScale.z);
            break;
        case Stretch.Vertical:
            _thisTransform.localScale = new Vector3(_thisTransform.localScale.x, h,_thisTransform.localScale.z);
            break;
        case Stretch.Both:
            _thisTransform.localScale = new Vector3(ratioScale, h,_thisTransform.localScale.z);
            break;
        default:break;
        }
    }
}

答案 1 :(得分:0)

首先,我想说没有好的解决方案,只有不那么糟糕。

最简单的方法就是支持一种宽高比,这样你就可以在不失真的情况下上下缩放所有内容,但几乎从来都不是一种选择。

第二个最简单的方法是让游戏采用一个宽高比并在边缘添加黑条(或其他东西),使实际游戏区域具有相同的宽高比。

如果您仍然需要不同的宽高比,解决方案是增加游戏区域,但这可能会导致具有不同宽高比的人获得优势,因为他们可以进一步提前或更高,这可能会弄乱您的关卡设计。

我刚刚发布了一个答案,只要你在这里有持续的宽高比,如何让一切都自动运作https://stackoverflow.com/a/25160299/2885785