【问题标题】:Using the Android gyroscope in Unity3d, how can I set the initial camera rotation to the initial mobile device rotation?在 Unity3d 中使用 Android 陀螺仪,如何将初始相机旋转设置为初始移动设备旋转?
【发布时间】:2014-11-13 10:56:41
【问题描述】:

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

【问题讨论】:

    标签: c# android unity3d gyroscope


    【解决方案1】:

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

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

    【讨论】:

    • @tuyga 回答你的问题了吗?
    • 有没有办法锁定Z轴。转动手机转圈时,Z轴松动,即使设置为0,旋转值仍在变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多