main
Yogi 2024-12-01 17:42:40 +08:00
parent 41e356aa79
commit 5a0445f150
1 changed files with 22 additions and 4 deletions

View File

@ -16,8 +16,6 @@ public class GameManager : MonoBehaviour
public bool isTestInput = false;
float angleX, angleY, angleZ;
public float smoothValue = 100;
public void Awake()
{
SampleMessageListener.OnReceivedMSG += OnReceivedMessage;
@ -61,8 +59,8 @@ public class GameManager : MonoBehaviour
if (isCanControlModel)
{
//ControlModelRotate(new Vector3(filteredRoll, filteredPitch, angleZ)); // 传入过滤后的值
var result = CalculateRotation(brainTrans.rotation, ax, ay, az, gx, gy, gz);
brainTrans.rotation = Quaternion.Slerp(brainTrans.rotation, result, Time.deltaTime * smoothValue);
//brainTrans.rotation = CalculateRotation(brainTrans.rotation, ax, ay, az, gx, gy, gz);
CalculateRotation(ax, ay, az, gx, gy, gz);
}
}
}
@ -80,6 +78,26 @@ public class GameManager : MonoBehaviour
{
brainTrans.rotation = Quaternion.Euler(angleModify);
}
private void CalculateRotation(float ax, float ay, float az, float gx, float gy, float gz)
{
// 通过加速度计算姿态(俯仰角和滚转角)
float roll = Mathf.Atan2(ay, az) * Mathf.Rad2Deg; // 滚转角
float pitch = Mathf.Atan2(-ax, Mathf.Sqrt(ay * ay + az * az)) * Mathf.Rad2Deg; // 俯仰角
// 计算角速度的变化(可以设定角速度的阈值或限制其过快变化)
angleX += gx * dt; // 绕X轴旋转
angleY += gy * dt; // 绕Y轴旋转
angleZ += gz * dt; // 绕Z轴旋转
// 使用互补滤波来平滑姿态估计
// 这里的系数决定了加速度和陀螺仪的权重通常设置为0.98
float alpha = 0.98f; // 互补滤波的权重
float filteredPitch = alpha * (angleX) + (1 - alpha) * pitch; // 过滤后的俯仰角
float filteredRoll = alpha * (angleY) + (1 - alpha) * roll; // 过滤后的滚转角
brainTrans.rotation = Quaternion.Euler(new Vector3(filteredRoll, filteredPitch, angleZ));
}
private Quaternion CalculateRotation(Quaternion rotation, float ax, float ay, float az, float gx, float gy, float gz)
{
// 假设你已经有初始四元数