Unity陀螺仪重置摄像机位置(如眼睛重新定位摄像机)

时间:2016-08-01 04:51:38

标签: android ios unity3d camera gyroscope

我正在为android / ios制作一个启用陀螺仪的应用程序,你可以用你的陀螺仪环顾四周。我希望播放器重置他们的摄像头位置(重新设置设备前面的场景),但是我无法让系统为此工作。

以下是环顾四周的代码:

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
            }
        }
    }
}

1 个答案:

答案 0 :(得分: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);
            }
        }
    }
}