2d游戏开发为了始终让物体在摄像机视野范围内,要保持size的大小为屏幕高度的一半。使用比值法。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AspectRadio2D : MonoBehaviour
{
Camera cam;
public int DesignHalfWidth; //一半的宽度
public int DesignHalfHeight; //一半
public int pixofperunit = 100;
float designRadio
{
get
{
return (float)DesignHalfWidth / DesignHalfHeight;
}
}
float realRadio
{
get
{
return (float)Screen.width / Screen.height;
}
}
void Start()
{
cam = transform.GetComponent<Camera>();
}
void Update()
{
Debug.Log(realRadio);
if (designRadio<realRadio)
{
//当前分辨率大于设计分辨率,unity会自动缩放,加个判断,减少计算量
cam.orthographicSize = (float)DesignHalfHeight/pixofperunit;
}
else
{
float radio = designRadio / realRadio;
cam.orthographicSize = DesignHalfHeight / (radio* pixofperunit);
}
}
}