使用 unity3d 获取设备的方向

get the orientation of the device with unity3d

我正在用 unity 制作我的第一个 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 之类的内容。但是这个 属性 应该可以满足您的需求。您只需要测试不同的方向,看看什么对您有意义。

示例:

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 class 获取显示分辨率。一个简单的横向检查是:

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