1. 程式人生 > >關於Unity3D螢幕適配的簡單處理方法

關於Unity3D螢幕適配的簡單處理方法

第一次寫文章!

unity3d 開發專案適配問題處理,實現的結果是寬高比超出的部分相機直接裁掉留黑,如果要加背景可以再掛一個相機填補黑色,程式碼以橫屏為例

using UnityEngine;

/// <summary>
/// 螢幕適配
/// </summary>
[RequireComponent(typeof(Camera))]
public class ScreenAdapt : MonoBehaviour
{
	public float screenHeight;
	public float screenWidth;

	void Start()
	{
		UpdateCamera ();
	}
	
	void UpdateCamera ()
	{
		screenHeight = Screen.height;
		screenWidth = Screen.width;

		Rect r = new Rect();
		if(screenHeight / screenWidth > 0.61f)//更方的螢幕 480*800
		{
			r.width = 1;
			r.height = (screenWidth * 0.61f) / screenHeight;
			r.x = 0;
			r.y = (1 - r.height) / 2f;
		}	
		else if(screenHeight / screenWidth < 0.56f)//更長的螢幕480*854
		{
			
			r.width = (screenHeight / 0.56f) / screenWidth;
			r.height = 1f;
			r.x = (1 - r.width) / 2f;
			r.y = 0;
		}
		else //在可適配區域不做處理480*800 - 480*854之間的
		{
			r.width = 1;
			r.height = 1;
			r.x = 0;
			r.y = 0f;
		}
		GetComponent<Camera>().rect = r;
	}
}

直接將指令碼掛在需要適配的相機上即可,

原理就是修改的相機的視口

這樣處理後,即可完美適配,建議pause/resume 後做一次重新整理

http://blog.csdn.net/c5138891/article/details/52512881