Unity3D学习笔记之陀螺仪的使用

发表于2017-02-23
评论0 2.3k浏览
  前面教给如何去调用手机陀螺仪,下面就给大家介绍下Unity3D中陀螺仪的使用,一起来看看吧。
  
  首先,我们需要在场景中添加大量方块,作为观察对象。
  
  控制陀螺仪的脚本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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文件,安装到带有陀螺仪的手机就可以了。运行后会看到,当手机位姿变化时,方块也会随着变化。但是手机陀螺仪会有少许漂移。当手机不动时候,场景中的方块也许会有少量移动。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引