Unity3D中手机陀螺仪的使用

转自Unity3D中手机陀螺仪的使用


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

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

Unity3D中手机陀螺仪的使用


       控制陀螺仪的脚本:

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class gyroscope : MonoBehaviour {  
  5.   
  6.     bool draw = false;  
  7.     bool gyinfo;  
  8.     Gyroscope go;  
  9.     void Start()  
  10.     {  
  11.         gyinfo = SystemInfo.supportsGyroscope;  
  12.         go = Input.gyro;  
  13.         go.enabled = true;  
  14.     }  
  15.     void Update()  
  16.     {  
  17.         if (gyinfo)  
  18.         {  
  19.             Vector3 a = go.attitude.eulerAngles;  
  20.             a = new Vector3(-a.x, -a.y, a.z); //直接使用读取的欧拉角发现不对,于是自己调整一下符号  
  21.             this.transform.eulerAngles = a;  
  22.             this.transform.Rotate(Vector3.right * 90, Space.World);          
  23.             draw = false;  
  24.         }  
  25.         else  
  26.         {  
  27.             draw = true;  
  28.         }  
  29.     }  
  30.   
  31.     void OnGUI()  
  32.     {  
  33.         if (draw)  
  34.         {  
  35.             GUI.Label(new Rect(100, 100, 100, 30), "启动失败");  
  36.         }  
  37.     }  
  38.      
  39. }  

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


Unity3D中手机陀螺仪的使用