2016-08-01 238 views
2

我正在为android/ios制作陀螺仪启用的应用程序,您可以使用陀螺仪环视四周。我想让玩家重置他们的摄像头位置(设备的前景),但我无法得到一个系统为此工作。Unity陀螺仪重置摄像头位置(如oculus recenter摄像头)

这里是环视代码:

using UnityEngine; 
using System.Collections; 

public class CameraControl : MonoBehaviour { 
    void Start() { 
     if (SystemInfo.supportsGyroscope) { 
      Input.gyro.enabled = true; 

      //Create parent object and set this object's parent to that 
      GameObject camParent = new GameObject ("CamParent"); 
      camParent.transform.position = transform.position; 
      transform.parent = camParent.transform; 

      // Rotate the parent object by 90 degrees around the x axis 
      camParent.transform.Rotate (Vector3.right, 90); 
     } 
    } 

    void Update() { 
     if (SystemInfo.supportsGyroscope) { 
      Quaternion rotation = new Quaternion (Input.gyro.attitude.x, Input.gyro.attitude.y, -Input.gyro.attitude.z, -Input.gyro.attitude.w); 
      transform.localRotation = rotation; 
     } 
    } 

    void OnGUI() { 
     if (SystemInfo.supportsGyroscope) { 
      GUILayout.Label (transform.localRotation.ToString()); 
      GUILayout.Label (transform.parent.rotation.ToString()); 

      if (GUILayout.Button ("Recenter View")) { 
       //RECENTER THE CAMERA VIEW 
      } 
     } 
    } 
} 

回答

0

您需要添加一个原点旋转 - 由四元数是要重置旋转的反向旋转的旋转。

在你的情况,这将是:

using UnityEngine; 
using System.Collections; 

public class CameraControl : MonoBehaviour { 
    void Start() { 
     if (SystemInfo.supportsGyroscope) { 
      Input.gyro.enabled = true; 

      //Create parent object and set this object's parent to that 
      GameObject camParent = new GameObject ("CamParent"); 
      camParent.transform.position = transform.position; 
      transform.parent = camParent.transform; 

      // Rotate the parent object by 90 degrees around the x axis 
      camParent.transform.Rotate (Vector3.right, 90); 
     } 
    } 

    Quaternion origin = Quaternion.identity; 

    void Update() { 
     if (SystemInfo.supportsGyroscope) { 
      Quaternion rotation = new Quaternion (Input.gyro.attitude.x, Input.gyro.attitude.y, -Input.gyro.attitude.z, -Input.gyro.attitude.w); 
      transform.localRotation = rotation * origin; 
     } 
    } 

    void OnGUI() { 
     if (SystemInfo.supportsGyroscope) { 
      GUILayout.Label (transform.localRotation.ToString()); 
      GUILayout.Label (transform.parent.rotation.ToString()); 

      if (GUILayout.Button ("Recenter View")) { 
       //RECENTER THE CAMERA VIEW 
       origin = Quaternion.Inverse(transform.localRotation); 
      } 
     } 
    } 
} 
+0

不工作,使视图中的所有侧身搞砸 –

+0

也许你得到了算法错了或什么? –

+0

我的android设备崩溃了,目前无法进行调试。请在此期间尝试以下操作:https://gist.github.com/chanibal/baf46307c4fee3c699d5 您可能想要反转旋转(将第23行更改为'transform.localRotation = Quaternion.Inverse(Quaternion.Inverse(origin)* Input .gyro.attitude);') –