在Unity3d中使用Android陀螺仪,如何将初始摄像机旋转设置为初始移动设备旋转?

时间:2014-11-13 10:56:41

标签: c# android unity3d gyroscope

我想使用Android陀螺仪在Unity3d的标准第一人称控制器上执行头部跟踪。我创建了一个简短的脚本来旋转第一人称控制器的父节点和相机子节点。脚本附在相机上。

此脚本运行良好,它根据我的移动设备的移动旋转第一人称视图。但是,它只有在我启动应用程序时将手机放在前视位置时才有效。如果我的手机平放在桌子上并启动我的应用程序,相机和陀螺仪旋转都会关闭。

我希望我的脚本尊重初始设备轮换。当我启动我的应用程序并且我的设备屏幕已启动时,相机应该首先查找。如何修改脚本以将相机旋转设置为初始移动设备旋转?

using UnityEngine;
using System.Collections;

// Activate head tracking using the gyroscope
public class HeadTracking : MonoBehaviour {
    public GameObject player; // First Person Controller parent node
    public GameObject head; // First Person Controller camera

    // Use this for initialization
    void Start () {
        // Activate the gyroscope
        Input.gyro.enabled = true;
    }

    // Update is called once per frame
    void Update () {
        // Rotate the player and head using the gyroscope rotation rate
        player.transform.Rotate (0, -Input.gyro.rotationRateUnbiased.y, 0);
        head.transform.Rotate (-Input.gyro.rotationRateUnbiased.x, 0, Input.gyro.rotationRateUnbiased.z);
    }
}

1 个答案:

答案 0 :(得分:9)

只需将初始方向保存在两个变量中,您的代码就会变为:

using UnityEngine;
using System.Collections;

// Activate head tracking using the gyroscope
public class HeadTracking : MonoBehaviour {
    public GameObject player; // First Person Controller parent node
    public GameObject head; // First Person Controller camera

    // The initials orientation
    private int initialOrientationX;
    private int initialOrientationY;
    private int initialOrientationZ;

    // Use this for initialization
    void Start () {
        // Activate the gyroscope
        Input.gyro.enabled = true;

        // Save the firsts values
        initialOrientationX = Input.gyro.rotationRateUnbiased.x;
        initialOrientationY = Input.gyro.rotationRateUnbiased.y;
        initialOrientationZ = -Input.gyro.rotationRateUnbiased.z;
    }

    // Update is called once per frame
    void Update () {
        // Rotate the player and head using the gyroscope rotation rate
        player.transform.Rotate (0, initialOrientationY -Input.gyro.rotationRateUnbiased.y, 0);
        head.transform.Rotate (initialOrientationX -Input.gyro.rotationRateUnbiased.x, 0, initialOrientationZ + Input.gyro.rotationRateUnbiased.z);
    }
}
相关问题