Unity實現對移動端的陀螺儀控制
阿新 • • 發佈:2019-02-20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GyroController : MonoBehaviour
{
public bool gyroEnabled = false;
public static GyroController _Instance;
void Awake()
{
_Instance = this;
}
#region [Private fields]
private const float lowPassFilterFactor = 0.2f;
private readonly Quaternion baseIdentity = Quaternion.Euler(90, 0, 0);
private readonly Quaternion landscapeRight = Quaternion.Euler(0, 0, 90);
private readonly Quaternion landscapeLeft = Quaternion.Euler(0, 0, -90);
private readonly Quaternion upsideDown = Quaternion.Euler(0 , 0, 180);
private Quaternion cameraBase = Quaternion.identity;
private Quaternion calibration = Quaternion.identity;
private Quaternion baseOrientation = Quaternion.Euler(90, 0, 0);
private Quaternion baseOrientationRotationFix = Quaternion.identity;
private Quaternion referanceRotation = Quaternion.identity;
private bool debug = true;
#endregion
protected void Start()
{
AttachGyro();
}
protected void Update()
{
if (!gyroEnabled)
return;
transform.rotation = Quaternion.Slerp(transform.rotation,
cameraBase * (ConvertRotation(referanceRotation * Input.gyro.attitude) * GetRotFix()), lowPassFilterFactor);
}
private void AttachGyro()
{
gyroEnabled = true;
ResetBaseOrientation();
UpdateCalibration(true);
UpdateCameraBaseRotation(true);
RecalculateReferenceRotation();
}
private void DetachGyro()
{
gyroEnabled = false;
}
private void UpdateCalibration(bool onlyHorizontal)
{
if (onlyHorizontal)
{
var fw = (Input.gyro.attitude) * (-Vector3.forward);
fw.z = 0;
if (fw == Vector3.zero)
{
calibration = Quaternion.identity;
}
else
{
calibration = (Quaternion.FromToRotation(baseOrientationRotationFix * Vector3.up, fw));
}
}
else
{
calibration = Input.gyro.attitude;
}
}
private void UpdateCameraBaseRotation(bool onlyHorizontal)
{
if (onlyHorizontal)
{
var fw = transform.forward;
fw.y = 0;
if (fw == Vector3.zero)
{
cameraBase = Quaternion.identity;
}
else
{
cameraBase = Quaternion.FromToRotation(Vector3.forward, fw);
}
}
else
{
cameraBase = transform.rotation;
}
}
private static Quaternion ConvertRotation(Quaternion q)
{
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
private Quaternion GetRotFix()
{
return Quaternion.identity;
}
private void ResetBaseOrientation()
{
baseOrientationRotationFix = GetRotFix();
baseOrientation = baseOrientationRotationFix * baseIdentity;
}
private void RecalculateReferenceRotation()
{
referanceRotation = Quaternion.Inverse(baseOrientation) * Quaternion.Inverse(calibration);
}
}
使用的時候只需要在自己的程式碼段中新增
Input.gyro.enabled = false(true);
GyroController._Instance.gyroEnabled = false(true);
即可現實陀螺儀控制,當然前提是移動裝置有陀螺儀。