Unity 手机的旋转控制

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScreenRotate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Screen.orientation = ScreenOrientation.LandscapeLeft;
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.deviceOrientation == DeviceOrientation.LandscapeLeft)
        {
            if(Screen.orientation != ScreenOrientation.LandscapeLeft)
            {
                Screen.orientation = ScreenOrientation.LandscapeLeft;
            }

            Debug.Log("### 111: " + Screen.orientation);
        }
        else if(Input.deviceOrientation == DeviceOrientation.LandscapeRight)
        {
            if (Screen.orientation != ScreenOrientation.LandscapeRight)
            {
                Screen.orientation = ScreenOrientation.LandscapeRight;
            }

            Debug.Log("### 222: " + Screen.orientation);
        }
	}
}

注意几点:

1.Input.deviceOrientation

文档描述:Device physical orientation as reported by OS. (Read Only)

解释:用于实时获取手机当前所处的方向


2.Screen.orientation

解释:用于设置当前屏幕内容的方向

特殊说明当我们设置该变量的值为:ScreenOrientation.AutoRotation的时候,他会自动根据手机所处的方向,自动设置真实的值,取值范围根据以下变量设置

autorotateToLandscapeLeft Allow auto-rotation to landscape left?
autorotateToLandscapeRight Allow auto-rotation to landscape right?
autorotateToPortrait Allow auto-rotation to portrait?
autorotateToPortraitUpsideDown Allow auto-rotation to portrait, upside down?
这4个变量共同决定了AutoRotation的取值范围,如果4个变量中有为false的,那么将会从取值范围中移除。


3.Screen.orientation = ScreenOrientation.LandscapeLeft;

这样赋值后,屏幕将永远相对于在home键的左侧,无论我们怎么旋转手机,都不会让屏幕进行旋转了。如果我们要旋转屏幕内容,那么就得像Update函数中那样做,进行手动检测控制


4.测试中发现给Screen.orientation赋值后,如果立刻获取Screen.orientation的值,会发现并没有改变为赋值之后的,而要等待手机旋转的过渡动画完成后,再获取Screen.orientation的值,才是我们赋予的。这条把我坑惨了,因为项目里面我会在同一帧使用Screen.orientation的值做一些逻辑,发现不对头,所以后来打印了该值,才发现这个问题,解决办法就是我用变量缓存了我们要赋予的值,再做逻辑就行了。


猜你喜欢

转载自blog.csdn.net/qweewqpkn/article/details/80934434