unity的3D相機默認是根據(jù)高度適配的(保持3D相機的高度視野范圍不變),這里調整成根據(jù)寬度適配(就是保持3D相機寬度的視野范圍不變)。
直接上腳本,將腳本掛在Camera的物體上
//=====================================================
// - FileName: CameraAdjust.cs
// - Description:
// - Author: wangguoqing
// - Email: wangguoqing@hehemj.com
// - Created: #CreateTime#
// - UserName: #AuthorName#
// - (C) Copyright 2008 - 2015, hehehuyu,Inc.
// - All Rights Reserved.
//======================================================
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 3D相機根據(jù)寬度適配,默認的相機是根據(jù)高度適配的
/// 將該腳本掛在Camera的物體上
/// </summary>
public class CameraAdjust : MonoBehaviour {
void Start ()
{
int ManualWidth = 1280; //首先記錄下你想要的屏幕分辨率的寬
int ManualHeight = 720; //記錄下你想要的屏幕分辨率的高 //普通安卓的都是 1280*720的分辨率
int manualHeight;
//然后得到當前屏幕的高寬比 和 你自定義需求的高寬比。通過判斷他們的大小,來不同賦值
//*其中Convert.ToSingle()和 Convert.ToFloat() 來取得一個int類型的單精度浮點數(shù)(C#中沒有 Convert.ToFloat() );
if (Convert.ToSingle(Screen.height) / Screen.width > Convert.ToSingle(ManualHeight) / ManualWidth)
{
//如果屏幕的高寬比大于自定義的高寬比 。則通過公式 ManualWidth * manualHeight = Screen.width * Screen.height;
//來求得適應的 manualHeight ,用它待求出 實際高度與理想高度的比率 scale
manualHeight = Mathf.RoundToInt(Convert.ToSingle(ManualWidth) / Screen.width * Screen.height);
}
else
{ //否則 直接給manualHeight 自定義的 ManualHeight的值,那么相機的fieldOfView就會原封不動
manualHeight = ManualHeight;
}
Camera camera = GetComponent<Camera>();
float scale = Convert.ToSingle(manualHeight*1.0f / ManualHeight);
camera.fieldOfView *= scale; //Camera.fieldOfView 視野: 這是垂直視野:水平FOV取決于視口的寬高比,當相機是正交時fieldofView被忽略
//把實際高度與理想高度的比率 scale乘加給Camera.fieldOfView。
//這樣就能達到,屏幕自動調節(jié)分辨率的效果
}
}