2016-08-01 235 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);') –