Unity 用陀螺儀+加速度計 控制 Camera 旋轉

這個是用 陀螺儀+加速度計 同時採樣,避免陀螺儀飄移,但是目前只能避免 X, Z 的漂移,所以 Y 還是會飄移,那是因為加速度計無法判斷 Y 的旋轉,未來會加入 “電子指南針(磁力計)” 來校正 Y。目前用 X, Z 在一些高端的手機上其實跑的也很穩,不怎麼飄,所以還是可以用的,你們玩玩看吧,把這個腳本掛在 Camera 或 父物件上,在手機上就能按照你想要的旋轉啦。

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

public class DeviceState : MonoBehaviour
{   
    public float X = 0;
    public float Y = 0;
    public float Z = 0;

    void Start ()
    {
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        Input.gyro.enabled = true;
        Input.gyro.updateInterval = 0.005f;
    }

    float[] xx = new float[10];
    float[] zz = new float[10];

    void Update ()
    {
        float accX = Input.acceleration.x;
        float accY = Input.acceleration.y;
        float accZ = Input.acceleration.z;

        float x = 180 / Mathf.PI * Mathf.Atan (accZ / accY);
        float z = 180 / Mathf.PI * Mathf.Atan (accX / accY);

        xx [0] = xx [1];
        xx [1] = xx [2];
        xx [2] = xx [3];
        xx [3] = xx [4];
        xx [4] = xx [5];
        xx [5] = xx [6];
        xx [6] = xx [7];
        xx [7] = xx [8];
        xx [8] = xx [9];
        xx [9] = x;

        x = (xx [0] + xx [1] + xx [2] + xx [3] + xx [4] + xx [5] + xx [6] + xx [7] + xx [8] + xx [9]) / 10;

        zz [0] = zz [1];
        zz [1] = zz [2];
        zz [2] = zz [3];
        zz [3] = zz [4];
        zz [4] = zz [5];
        zz [5] = zz [6];
        zz [6] = zz [7];
        zz [7] = zz [8];
        zz [8] = zz [9];
        zz [9] = z;

        z = (zz [0] + zz [1] + zz [2] + zz [3] + zz [4] + zz [5] + zz [6] + zz [7] + zz [8] + zz [9]) / 10;

        X += -Input.gyro.rotationRate.x;
        Y += -Input.gyro.rotationRate.y;
        Z += Input.gyro.rotationRate.z;

        X = (X + x) / 2;
        Z = (Z + z) / 2;

        transform.eulerAngles = new Vector3 (X, Y, Z);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38884324/article/details/79846847