使用 unity3d 获取设备的方向

Dan*_*son 3 c# 2d unity-game-engine

我正在制作我的第一个 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"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

I want to write out start game button if the orientation of the device is in landscape and the register if it is in portrait. Now it writes out Register button even though i play my game in landscape mode. What is wrong?

Zac*_*ker 6

Screen.orientation用于告诉应用程序如何处理设备方向事件。它可能实际上设置为ScreenOrientation.AutoOrientation. 分配给这个属性会指示应用程序切换到哪个方向,但从中读取并不一定会告诉您设备当前处于哪个方向。

使用设备方向

您可以使用Input.deviceOrientation来获取设备的当前方向。请注意,DeviceOrientation枚举是相当具体的,因此您的条件可能必须检查诸如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
Run Code Online (Sandbox Code Playgroud)

使用显示分辨率

您可以使用Screen该类获取显示分辨率。对景观的简单检查是:

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