Unity移动端自动翻转及横竖屏的设置与检测
Unity手动设置
手动设置程序方向File- - ->Build Settings- - ->PlayerSettings- - ->Resolution and Presentation- - ->Orientation。如下图所示。
所能设置的值有:
- Portrait:设备在纵向模式,设备直立并home按钮在底部。
- PortraitUpsideDown:设备在纵向模式,但颠倒一下,设备直立并home按钮在顶部。
- LandscapeLeft:设备在横向模式,设备直立并home按钮在右边。
- LandscapeRight:设备在横向模式,设备直立并home按钮在左边。
- Auto Rotation:设备可以自由旋转,在上面的模式中自由切换。
代码设置与检测
使用代码设置检测,有两种方式可用:Screen.orientation
或Input.deviceOrientation
。
Screen.orientation
这是Unity自带的一个静态属性。其实就是上面介绍的手动设置的代码方式,只是其枚举多了一个Unknown
。是屏幕的显示方向。
当手动设置为一个固定的模式时,是没有必要实时检测的,除非处于Auto Rotation模式。
具体检测用法如下面的示例:
if (Screen.orientation == ScreenOrientation.Portrait)
transform.localEulerAngles = new Vector3(0, 180, 90);
else if (Screen.orientation == ScreenOrientation.PortraitUpsideDown)
transform.localEulerAngles = new Vector3(0, 180, 180);
else if (Screen.orientation == ScreenOrientation.LandscapeLeft)
transform.localEulerAngles = new Vector3(0, 180, 0);
else if (Screen.orientation == ScreenOrientation.LandscapeRight)
transform.localEulerAngles = new Vector3(0, 180, 180);
else if (Screen.orientation == ScreenOrientation.AutoRotation)
StartCoroutine(func());
Screen.autorotateToPortrait = false;
则屏幕不会翻转成竖屏,类似的对Screen.autorotateToLandscapeLeft
、Screen.autorotateToLandscapeRight
和Screen.autorotateToPortraitUpsideDown
也可以有相似的操作。
Input.deviceOrientation
这也是一个Unity自带的一个静态属性,其实就是移动设备陀螺仪的状态属性接口。其枚举的值要比Screen.orientation
多。分别有:
- Unknown:设备的方向不能被确定。
- Portrait:设备在纵向模式,设备直立并home按钮在底部。
- PortraitUpsideDown:设备在纵向模式,但颠倒一下,设备直立并home按钮在顶部。
- LandscapeLeft:设备在横向模式,设备直立并home按钮在右边。
- LandscapeRight:设备在横向模式,设备直立并home按钮在左边。
- FaceUp:设备保持与地面平行,屏幕的面向上。
- FaceDown:设备保持与地面平行,屏幕的面向下。
具体用法如下面的示例:
if (Input.deviceOrientation == DeviceOrientation.Portrait)
transform.localEulerAngles = new Vector3(0, 180, 90);
else if (Input.deviceOrientation == DeviceOrientation.PortraitUpsideDown)
transform.localEulerAngles = new Vector3(0, 180, 180);
else if (Input.deviceOrientation == DeviceOrientation.LandscapeLeft)
transform.localEulerAngles = new Vector3(0, 180, 0);
else if (Input.deviceOrientation == DeviceOrientation.LandscapeRight)
transform.localEulerAngles = new Vector3(0, 180, 180);
这个属性即使在Screen.orientation
的模式固定的情况下,依然可以检测到移动设备陀螺仪的朝向状态。