unity手机端指南针安卓测试有效

创建如图游戏对象,
注意指南针初始旋转值为0,0,0,而且图片北方朝向正前方

新建脚本Compass.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Compass : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Input.compass.enabled = true;
    }
    //百度一下利用Input.compass实现指北针


    //OnGUI的调用次数
    void OnGUI()
    {
        //Input.location.Start();
        ////地理北极就是北方,也是磁南极
        //GUILayout.Label(" rawVector: " + Input.compass.rawVector.ToString() //用microteslas测量的原始地磁数据
        //    + " trueHeading: " + Input.compass.trueHeading.ToString()   //相对应地理北极的度数
        //    + " headingAccuracy: " + Input.compass.headingAccuracy.ToString() //标题度数的准确度
        //    + " magneticHeading: " + Input.compass.magneticHeading.ToString(), GUILayout.Width(5000), GUILayout.Width(200));//相对于磁北极的度数
    }
    [SerializeField] Text text;
    [SerializeField] Text text1;
    [SerializeField] Text text2;
    [SerializeField] Text text3;
    [SerializeField] Image compass;
    float dushu = 0;//记录北方度数
    float tempdushu = 0;//临时记录数据来判断角度变化是否大于2
    // Update is called once per frame
    void FixedUpdate () {
        //如何确定参照物
        //当度数为  358-2度  手机的正前方就是北方



        Input.location.Start();
        text.text = " rawVector: " + Input.compass.rawVector.ToString();//用microteslas测量的原始地磁数据

        //相对应地理北极的度数 手机头正对方向  北方360/0   东方90     西方180    南方270  
        text1.text = " trueHeading: " + Input.compass.trueHeading.ToString();   
      
        text2.text = " headingAccuracy: " + Input.compass.headingAccuracy.ToString(); //标题度数的准确度
        text3.text = " magneticHeading: " + Input.compass.magneticHeading.ToString();////相对于磁北极的度数
        dushu = Input.compass.trueHeading;

        /*trueHeading          image/z
      北方358  360 0 2                0
       东方88  92                   90
       南方269 272                 270
       西方180                    180


        */

        //为防止抖动  度数变化超过二的时候才赋值
        if (Mathf.Abs(tempdushu-dushu)>3)
        {
            tempdushu = dushu;
            compass.transform.eulerAngles = new Vector3(0, 0, dushu);
        }
          
        
    }
}

然后挂载脚本,拖相关Text,以及Image

,然后打包到手机测试即可,图片最尖的地方就是北方

猜你喜欢

转载自blog.csdn.net/weixin_41995872/article/details/85230246