前言
当iphone开启锁定屏幕旋转的时候,使用Screen.orientation
就可以获知设备方向,但当设置为下图
或者
时,仍然需要强制旋转屏幕,就可以使用陀螺仪判断设备朝向。
代码
使用时把Text
文本删除,添加OnDeviceRotation
监听即可。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DeviceRotationHelper : MonoBehaviour
{
/// <summary>
/// 提示文字
/// </summary>
public Text text;
/// <summary>
/// 当设备旋转时触发
/// </summary>
public Action<DeviceOrientation> OnDeviceRotation;
/// <summary>
/// 当前设备旋转方向
/// </summary>
private DeviceOrientation currentDeviceOrientation;
/// <summary>
/// 当前设备旋转方向
/// </summary>
private DeviceOrientation CurrentDeviceOrientation {
get {
return currentDeviceOrientation;
}
set {
if (value != currentDeviceOrientation)
{
currentDeviceOrientation = value;
OnDeviceRotation?.Invoke(value);
text.text = currentDeviceOrientation.ToString();
}
}
}
void Update()
{
//每帧判断设备方向
CheckOrientation();
}
/// <summary>
/// 检查设备朝向
/// </summary>
void CheckOrientation()
{
if (Mathf.Abs(Input.gyro.gravity.z) <= 0.9f)
{
if (Mathf.Abs(Input.gyro.gravity.x) > Mathf.Abs(Input.gyro.gravity.y))
{
if (Input.gyro.gravity.x > 0f)
{
CurrentDeviceOrientation = DeviceOrientation.LandscapeRight;
}
else
{
CurrentDeviceOrientation = DeviceOrientation.LandscapeLeft;
}
}
else if (Input.gyro.gravity.y > 0f)
{
CurrentDeviceOrientation = DeviceOrientation.PortraitUpsideDown;
}
else
{
CurrentDeviceOrientation = DeviceOrientation.Portrait;
}
}
}
}