Unity3D中手机陀螺仪的使用

        使用手机陀螺仪,可以获取手机的3D姿态,这在开发中是很有用的。当然现在的手机内置的陀螺仪都是比较廉价的,精度不高,但是作为实验设备看看效果还是可以的。本文将给出调用手机陀螺仪的简单方法。

       首先,我们需要在场景中添加大量方块,作为观察对象。



       控制陀螺仪的脚本:

using UnityEngine;
using System.Collections;

public class gyroscope : MonoBehaviour {

    bool draw = false;
    bool gyinfo;
    Gyroscope go;
    void Start()
    {
        gyinfo = SystemInfo.supportsGyroscope;
        go = Input.gyro;
        go.enabled = true;
    }
    void Update()
    {
        if (gyinfo)
        {
            Vector3 a = go.attitude.eulerAngles;
            a = new Vector3(-a.x, -a.y, a.z); //直接使用读取的欧拉角发现不对,于是自己调整一下符号
            this.transform.eulerAngles = a;
            this.transform.Rotate(Vector3.right * 90, Space.World);        
            draw = false;
        }
        else
        {
            draw = true;
        }
    }

    void OnGUI()
    {
        if (draw)
        {
            GUI.Label(new Rect(100, 100, 100, 30), "启动失败");
        }
    }
   
}

        该脚本绑定到主摄像机上,发布成apk文件,安装到带有陀螺仪的手机就可以了。运行后会看到,当手机位姿变化时,方块也会随着变化。但是手机陀螺仪会有少许漂移。当手机不动时候,场景中的方块也许会有少量移动。






原文地址:https://www.cnblogs.com/yanhuiqingkong/p/7770084.html