Unity3D -- 獲取遊戲螢幕的寬高
這裡要用到一個攝像機函式Camera.ViewportToWorldPoint, Unity官方對其定義為:
Camera.ViewportToWorldPoint 視窗轉世界位置
function ViewportToWorldPoint (position : Vector3) : Vector3
Description描述
Transforms position from viewport space into world space.
從視窗空間到世界空間的變換位置。
Viewport space is normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). The z position is in world units from the camera.
視口空間是歸一化的並相對於相機的,相機的左下為(0,0);右上是(1,1);Z的位置是以世界單位衡量的到相機的距離。
Note that it transforms a x-y screen position, into a x-y-z position in 3D space.
請注意它是變換一個x-y螢幕位置到一個3D空間的x-y-z位置。
You provide the function with a vector where the x-y components of the vector are the screen coordinates and the z component is the distance of the resulting plane from the camera.
這個函式帶有在螢幕座標的x-y元件向量,並且z元件是在從相機產生的平面的距離。
看了官方文件,現在我們知道怎麼獲取螢幕的實際寬高,下面是示例程式碼:
private float width;
private float height;
void SetBasicValues(){
float leftBorder;
float rightBorder;
float topBorder;
float downBorder;
//the up right corner
Vector3 cornerPos=Camera.main .ViewportToWorldPoint(new Vector3(1f,1f,Mathf.Abs(Camera.main.transform.position.z)));
leftBorder=Camera.main.transform.position.x-(cornerPos.x-Camera.main.transform.position.x);
rightBorder=cornerPos.x;
topBorder=cornerPos.y;
downBorder=Camera.main.transform.position.y-(cornerPos.y-Camera.main.transform.position.y);
width=rightBorder-leftBorder;
height=topBorder-downBorder;
}
得到的width與height就是螢幕寬高,程式碼的含義上面已經說的很清楚了。