在 Unity3d 中使用安卓陀螺仪,如何将初始相机旋转设置为初始移动设备旋转

本文关键字:旋转 相机 设置 移动 Unity3d 陀螺 | 更新日期: 2023-09-27 18:30:17

我想使用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);
    }
}

在 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
    // 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);
    }
}