using UnityEngine; public class GameManager : MonoBehaviour { public string startMsg = "START"; public string stopMsg = "STOP"; public AudioPlayControl videoControl; private bool isCanControlModel = false; public Transform brainTrans; public float dt = 0.1f; public bool isTestInput = false; float angleX, angleY, angleZ; public void Awake() { SampleMessageListener.OnReceivedMSG += OnReceivedMessage; brainTrans.gameObject.SetActive(false); } private void OnDestroy() { SampleMessageListener.OnReceivedMSG -= OnReceivedMessage; } private void OnReceivedMessage(string msgStr) { if (msgStr == startMsg) { print($"开始游戏"); GamePlay(); } else if (msgStr == stopMsg) { print($"退出游戏"); Application.Quit(); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #endif } else { var arr = msgStr.Split(','); //加速度 var ax = float.Parse(arr[0]); var ay = float.Parse(arr[1]); var az = float.Parse(arr[2]); //角速度 var gx = float.Parse(arr[3]); var gy = float.Parse(arr[4]); var gz = float.Parse(arr[5]); print($"获得加速度:{ax},{ay},{az}"); print($"获得角速度:{gx},{gy},{gz}"); if (isCanControlModel) { // 时间间隔 float dt = 0.01f; // 通过加速度计算姿态(俯仰角和滚转角) 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; // 过滤后的滚转角 ControlModelRotate(new Vector3(filteredRoll, filteredPitch, angleZ)); // 传入过滤后的值 } } } private async void GamePlay() { await videoControl.PlayStartVideo(); JustGamePlayNoAnim(); } private void JustGamePlayNoAnim() { isCanControlModel = true; brainTrans.gameObject.SetActive(true); } private void ControlModelRotate(Vector3 angleModify) { brainTrans.rotation = Quaternion.Euler(angleModify); } private void Update() { if (isTestInput) { if (Input.GetKeyDown(KeyCode.Alpha1)) { OnReceivedMessage(startMsg); } if (Input.GetKey(KeyCode.Alpha2)) { float randomF() => Random.Range(0.0f, 1.0f); OnReceivedMessage($"{randomF()},{randomF()},{randomF()},{randomF()},{randomF()},{randomF()}"); } else if (Input.GetKeyDown(KeyCode.Alpha3)) { OnReceivedMessage(stopMsg); } else if (Input.GetKeyDown(KeyCode.F)) { videoControl.StopPlay(); JustGamePlayNoAnim(); } } } }