使用 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 类获取显示分辨率。一个简单的景观检查是:

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

最新更新