开始上班了,写一下上班后的第一篇博客,关于unity相机视口自适应,16:9
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRectFix : MonoBehaviour
{
private Camera _camera;
private float _aspect;
private float _nowHeight;
private float _nowWidth;
private float _designAspect;
private float _nowH;
private float _nowW;
private float _screenHeight;
private float _screenWidth;
void Start()
{
_screenHeight = Screen.height;
_screenWidth = Screen.width;
_camera = GetComponent<Camera>();
_designAspect = 16f / 9f;
FixRect();
}
void CheckWindow()
{
if (_screenWidth != Screen.width||_screenHeight!=Screen.height)
{
Debug.Log("重设视口");
_screenWidth = Screen.width;
_screenHeight = Screen.height;
FixRect();
}
}
void Update()
{
CheckWindow();
}
public void FixRect()
{
_aspect = _screenWidth / _screenHeight;
if (_aspect>_designAspect)
{
_nowWidth = Screen.height * _designAspect;
_nowW = _nowWidth / Screen.width;
_camera.rect = new Rect((1-_nowW)/2f, 0f, _nowW,1f);
}
else
{
_nowHeight = Screen.width / _designAspect;
_nowH = _nowHeight / Screen.height;
_camera.rect = new Rect(0f, (1 - _nowH) / 2f, 1f,_nowH);
}
}
}
就这些
|