public class GyroControl : MonoBehaviour
{
private bool gyroEnabled;
private Gyroscope gyro;
private GameObject cameraContainer;
private Quaternion rot;
private void Start()
{
cameraContainer = new GameObject("Camera Container");
cameraContainer.transform.position = transform.position;
transform.SetParent(cameraContainer.transform);
gyroEnabled = EnableGyro();
}
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
cameraContainer.transform.rotation = Quaternion.Euler(90f, 0f, -90f);
rot = new Quaternion(0, 0, 1, 0);
return true;
}
return false;
}
private void Update()
{
if (gyroEnabled)
{
transform.localRotation = gyro.attitude * rot;
}
}
}
我有一个使用陀螺仪构建的游戏,但陀螺仪使用了世界旋转,我不想这样。每当我开始游戏时,我的手机方向会变成开始旋转的方向,我的意思是,如果我开始游戏,我会使用相同的相机旋转,并按陀螺仪范围值左右移动。
我试过这个:
private Quaternion initialRot;
/
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
initialRot = gyro.attitude;
cameraContainer.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
return true;
}
return false;
}
/
private void Update()
{
if (gyroEnabled)
{
transform.localRotation = gyro.attitude * Quaternion.Inverse(initialRot);
}
}
最后,我想让陀螺仪的价值建立在当前手机的之上
您的第二个脚本是最符合逻辑的解决方案。尝试使用矢量而不是四元数,因为它们应该更容易管理和调试。initialRot变量,将其转换为Vector3,在Update((方法中添加:
private Vector3 initialRot;
...
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
initialRot = gyro.attitude.eulerAngles;
cameraContainer.transform.rotation = Quaternion.Euler(0f, 0f, 0f);
return true;
}
return false;
}
...
private void Update()
{
if (gyroEnabled)
{
transform.localEulerAngles = gyro.attitude.eulerAngles + initialRot;
}
}