在我的Unity应用程序中,我想检测一下,如果一个横向倾斜的Android手机向上或向下倾斜 - 例如像这样:https://lh3.ggpht.com/A-9UCSQn7nujEMF5qmJir2YKIHbu3ehFneELSXprBBId_TYhVONTCd3guPUgQ-qte6GO=h900-rw
旋转矢量传感器可能是我正在寻找的工具,但我没有找到如何使用Unity访问它。 我不希望它依赖于速度,我只需要知道,如果手机正面向地板或天空。
如何检测旋转?
答案 0 :(得分:0)
我相信你必须使用Gyroscope.attitude
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
transform.rotation = Input.gyro.attitude;
}
}
参考:https://docs.unity3d.com/ScriptReference/Gyroscope-attitude.html
答案 1 :(得分:0)
正如@Demon 提到的,您需要使用 Input.gyro.attitude,但您需要注意以下几点:
#1 确保设备有陀螺仪:
if (!SystemInfo.supportsGyroscope)
{
// Exit with message
}
#2 确保开启陀螺仪
Input.gyro.enabled = true;
#3 将陀螺仪的右手坐标系转换为 Unity 的左手坐标系:
private static Quaternion GyroToUnity(Quaternion q)
{
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
*** 编辑 ***
这是获取手机倾斜方向的组件:
using System;
using UnityEngine;
using UnityEngine.UI;
public class Orientation : MonoBehaviour
{
public Text textComponent;
public GameObject blockText;
Gyroscope gyro;
float initAng;
const float angTolerance = 20;
Quaternion gyroCalibration;
void Start()
{
// Make sure device supprts Gyroscope
if (!SystemInfo.supportsGyroscope) throw new Exception("Device does not support Gyroscopoe");
gyro = Input.gyro;
gyro.enabled = true; // Must enable the gyroscope
textComponent = GameObject.Find("Text").GetComponent<Text>();
blockText = GameObject.Find("Block Text");
Quaternion attitude = Attitude();
initAng = Elevation(attitude);
}
// Update is called once per frame
void Update()
{
Quaternion attitude = Attitude();
float ang = Elevation(attitude) - initAng;
String dirStr;
if (ang < -angTolerance)
dirStr = "Down";
else if (ang > angTolerance)
dirStr = "Up";
else
dirStr = "Center";
textComponent.text = ang.ToString() + "\n" + dirStr; // +ang = up -ang = down
}
private Quaternion Attitude()
{
Quaternion rawAttitude = gyro.attitude; // Get the phones attitude in phone space
Quaternion attitude = GyroToUnity(rawAttitude); // Convert phone space to Unity space
return attitude;
}
private static Quaternion GyroToUnity(Quaternion q)
{
return Quaternion.Euler(90, 0, 0) * new Quaternion(q.x, q.y, -q.z, -q.w);
}
private static float Elevation(Quaternion attitude)
{
Vector3 dir = attitude * Vector3.forward; // Convert Quaterinon to Dir
Vector2 horizontalDir = new Vector2(dir.x, dir.z);
float horizontalDis = horizontalDir.magnitude;
float ang = Mathf.Atan2(dir.y, horizontalDis) * Mathf.Rad2Deg; // Calculate the elevation
return ang;
}
}
您可以只使用“deviceOrientation()”,但这样做有两个优点:
#1 您可以控制手机需要倾斜多远才能注册倾斜 使用 deviceOrientation 您必须在手机注册倾斜之前将手机倾斜很远
#2 它使用设备起始高度作为参考,以补偿用户通常将手机略微向下或向上保持
答案 2 :(得分:0)
实现这一目标的最简单方法之一是使用 Input.deviceOrientation。
if (Input.deviceOrientation == DeviceOrientation.Portrait)
或
if (Input.deviceOrientation == DeviceOrientation.LandscapeLeft)
您还可以检查: 未知、人像、PortraitUpsideDown、LandscapeLeft、LandscapeRight、FaceUp 和FaceDown。
看看: https://docs.unity3d.com/ScriptReference/Input-deviceOrientation.html