【问题标题】:get the orientation of the device with unity3d使用 unity3d 获取设备的方向
【发布时间】:2015-01-07 19:01:09
【问题描述】:

我正在制作我的第一个统一的 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"); 
    }
}

如果设备的方向是横向,我想写出开始游戏按钮,如果是纵向,我想写出寄存器。现在即使我在横向模式下玩游戏,它也会写出注册按钮。怎么了?

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    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");
    }
    

    【讨论】:

    • 我如何比较 input.deviceOrientation 以获取方向是否为横向?
    • 查看我对DeviceOrientation (docs.unity3d.com/ScriptReference/DeviceOrientation.html) 的回复中的超链接。这包含诸如DeviceOrientation.LandscapeLeft 之类的值,表示左侧带有主页按钮的横向设备。它还有一些其他更具体的值,例如与地面平行的设备,您可能也应该处理(即,许多应用程序在这种情况下默认为横向)。我在答案中添加了一个示例。
    • 我试过这个 Input.deviceOrientation == DeviceOrientation.LandscapeLeft || Input.deviceOrientation == DeviceOrientation.LandscapeRight 但它仍然不起作用。我开始认为,也许当您玩游戏并更改设备分辨率时,它实际上并没有在任何方向上模拟设备,即使例如说“WVGA Landscape 800x480”
    • 首先,请务必检查DeviceOrientation.LandscapeLeft || DeviceOrientation.LandscapeRight。这样,您就可以在任一方向上旋转设备。是的,我不认为更改显示分辨率与更改设备方向相同。我会用一种检查显示分辨率的方法来更新我的答案。
    • 非常感谢!但是如何在unity3d中模拟游戏是横向模式还是纵向模式?
    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多