首页 > 解决方案 > 平滑嘈杂的指南针 (Android)

问题描述

我正在制作一种 AR 体验,我想使用手机的指南针将玩家指向真正的北方,但我在平滑 Android 设备上的指南针读数时遇到了问题。到目前为止,我试验过的代码将一定数量的读数记录到一个队列中,将队列复制到一个列表中,然后一旦列表已满,它就会取所有读数的平均值。从这里我想在 -1 和 1 之间缩放读数,其中 0 代表南方。然后我希望这些数据用于旋转 GUI 层上的指南针图像。

数据远没有我想要的那么平滑,但这里是我到目前为止的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CompassSlider : MonoBehaviour
{
    public float reading;
    public Queue<float> data;
    private float[] dataList;
    public int maxData = 100;
    public int count;
    public float sum, average;

    public float dampening = 0.1f;
    public float rotationToNorth;

    // Use this for initialization
    void Start()
    {
        data = new Queue<float>();
        dataList = new float[maxData];
    }

    // Update is called once per frame
    void Update()
    {
        Input.location.Start();
        Input.compass.enabled = true;

        count = data.Count;

        if (data.Count > 0)
        {
            data.CopyTo(dataList, 0);
        }

        if (data.Count == maxData)
        {
            for (int i = 0; i < data.Count; i++)
            {
                sum += dataList[i];
            }
            if (Mathf.Abs(dataList[maxData - 1]) > 0)
            {
                average = sum / maxData;
                sum = 0;
                data.Clear();
                dataList = new float[maxData];

            }
        }

        if (data.Count >= maxData)
        {
            data.Dequeue();
        }

        reading = Mathf.Round(Input.compass.trueHeading);
        data.Enqueue(reading);

        if (count == maxData) {
            rotationToNorth = average / 180;
            rotationToNorth = (Mathf.Round(rotationToNorth * 10)) / 10;
            rotationToNorth = rotationToNorth - 1;
        }
    }
}

标签: c#androidunity3dcompass

解决方案


推荐阅读