簡體   English   中英

使用unity3d獲取設備的方向

[英]get the orientation of the device with unity3d

我用統一性制作了我的第一個2D游戲,然后嘗試做一個主菜單。

void OnGUI(){
    GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), MyTexture);
    if (Screen.orientation == ScreenOrientation.Landscape) {
        GUI.Button(new Rect(Screen.width * .25f, Screen.height * .5f, Screen.width * .5f, 50f), "Start Game"); 
    } else {
        GUI.Button(new Rect(0, Screen.height * .4f, Screen.width, Screen.height * .1f), "Register"); 
    }
}

如果設備的方向為橫向,我想寫出開始游戲按鈕,如果縱向為,我想寫出寄存器。 現在,即使我在橫向模式下玩游戲,它也會寫出“注冊”按鈕。 怎么了?

Screen.orientation用於告訴應用程序如何處理設備方向事件。 它實際上可能設置為ScreenOrientation.AutoOrientation 分配給該屬性將向應用程序指示要切換到的方向,但是從該方向讀取並不一定會通知您設備當前處於哪個方向。

使用設備方向

您可以使用Input.deviceOrientation獲取設備的當前方向。 請注意, DeviceOrientation枚舉是相當具體的,因此您的條件可能必須檢查DeviceOrientation.FaceUp類的DeviceOrientation.FaceUp 但是此屬性應該可以為您提供所需的東西。 您只需要測試不同的方向,看看什么對您有意義。

例:

if(Input.deviceOrientation == DeviceOrientation.LandscapeLeft || 
     Input.deviceOrientation == DeviceOrientation.LandscapeRight) {
    Debug.log("we landscape now.");
} else if(Input.deviceOrientation == DeviceOrientation.Portrait) {
    Debug.log("we portrait now");
}
//etc

使用顯示分辨率

您可以使用Screen類獲得顯示分辨率。 一個簡單的景觀檢查是:

if(Screen.width > Screen.height) {
    Debug.Log("this is probably landscape");
} else {
    Debug.Log("this is portrait most likely");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM