导语:
我们在进行游戏开发的时候为了让我们游戏在可以在各种机型上正常显示, 需要根据屏幕分辨率来调整游戏区域。
起初我只是简单的对游戏进行放大缩小和图片填充,但是这种方法在异形屏上虽然可以做到简单的适配,但是游戏内对象位置计算的难度会增加,产生逻辑混乱。
通过查资料和推理找到了一种更好的方式,就是改变摄像机(camera)的orthographic size,来进行适配。
1.创建一个Camera(摄像机),将Camera的Projection设置为orthographic
2.将Size属性设置为9.6(这个根据你的设计需求进行设置,我们的项目一般是在屏幕分辨率为(1080x1920)下进行开发的,size的值是屏幕高度的一半)
3.创建根据屏幕分辨率改变正交易大小的代码(下面的代码适用于竖屏适配至于横屏适配还需要进一步研究)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraAutoFix : MonoBehaviour
{
// 自动旋转允许的方向
//private allowedOrientationsForAutoRotation = Screen.
public void Awake()
{
ScreenOrientation designAutoRotation = Screen.orientation;
Camera _camera = this.gameObject.GetComponent<Camera>();
float aspect = _camera.aspect;
float designOrthographicSize = 9.6f;
float designHeight = 1920f;
float designWidth = 1080f;
float designAspect = designWidth / designHeight;
float widthOrthographicSize = designOrthographicSize * designAspect;
switch (designAutoRotation)
{
case ScreenOrientation.Portrait:
if(aspect < designAspect)
{
_camera.orthographicSize = widthOrthographicSize / aspect;
}
if (aspect > designAspect)
{
_camera.orthographicSize = designOrthographicSize;
//_camera.orthographicSize = designOrthographicSize * (aspect / designAspect);
}
break;
case ScreenOrientation.AutoRotation:
break;
case ScreenOrientation.LandscapeLeft:
break;
case ScreenOrientation.LandscapeRight:
break;
case ScreenOrientation.PortraitUpsideDown:
break;
default:
break;
}
}
}
4.将上面的脚本文件附加在Camera对象上,就可以适配大部分屏幕了。