ShootChecker_SDK.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using UnityEngine;
  2. namespace SmartBowSDK
  3. {
  4. /// <summary>
  5. /// 射箭检测器
  6. /// </summary>
  7. public class ShootChecker_SDK : MonoBehaviour
  8. {
  9. public SmartBowHelper smartBowHelper;
  10. /// <summary>
  11. /// 游戏里箭的速度
  12. /// </summary>
  13. public float gameArrowSpeed = 0;
  14. /// <summary>
  15. /// 游戏里箭的重量
  16. /// </summary>
  17. public float gameArrowWeight = 20;
  18. /// <summary>
  19. /// 现实里箭的重量
  20. /// </summary>
  21. public float solidArrowWeight = 75;
  22. /// <summary>
  23. /// 上一次的射击数据ID
  24. /// </summary>
  25. private int _lastShootID = -1;
  26. /// <summary>
  27. /// 当收到红外数据时
  28. /// </summary>
  29. /// <param name="bytes"></param>
  30. public void OnInfraredDataReceived(byte[] bytes)
  31. {
  32. //序号
  33. int id = bytes[1];
  34. if (id == _lastShootID) return; //因为硬件为了避免丢包,会连续发几条相同射击通知过来
  35. _lastShootID = id;
  36. //时区1耗时
  37. float time1 = bytes[2] * 0.1f;
  38. //时区2耗时
  39. float time2 = bytes[3] * 0.1f;
  40. //时区耗时总和
  41. float totalTime = time1 + time2;
  42. //校验和
  43. int sumCheck = (bytes[0] + bytes[1] + bytes[2] + bytes[3]) & 0xff;
  44. //校验和比较结果
  45. bool sumCheckRes = sumCheck == bytes[4];
  46. //实体箭速度
  47. float solidArrowSpeed = 0.05f / (totalTime / 1000f);
  48. //通过动能定理求箭的速度(实体箭质量*实体箭速度^2=游戏中箭的质量*游戏中箭的速度^2)
  49. gameArrowSpeed = Mathf.Sqrt(solidArrowSpeed * solidArrowSpeed * solidArrowWeight / gameArrowWeight);
  50. //打印
  51. string logInfo = $"序号{id},时区1:{time1}毫秒,时区2:{time2}毫秒,校验:{sumCheckRes},实体箭速度:{solidArrowSpeed}m/s,游戏箭速度:{gameArrowSpeed}m/s";
  52. SmartBowLogger.Log(this, logInfo);
  53. //收到正确的射箭数据,就回复硬件,否则n毫秒后硬件会认为丢包而进行重传
  54. if (sumCheckRes) smartBowHelper.bluetoothAim.ReplyInfraredShoot();
  55. //通知九轴算法,因为射箭抖动会使算法计算的姿态角产生误差
  56. smartBowHelper.aimHandler.NotifyAxisOnShot();
  57. smartBowHelper.InvokeOnShooting(gameArrowSpeed);
  58. }
  59. /// <summary>
  60. /// 回去枪指令
  61. /// </summary>
  62. /// <param name="bytes"></param>
  63. public void ReplyGun(byte[] bytes)
  64. {
  65. byte[] response = BluetoothDecryptor.GetResponse(bytes);
  66. smartBowHelper.bluetoothAim.ReplyByte(response);
  67. }
  68. /// <summary>
  69. /// 枪的弹夹状态
  70. /// 0x00 弹夹分离,0x01 上弹夹
  71. /// </summary>
  72. /// <param name="bytes"></param>
  73. public void UpdateTheMagazine(byte[] bytes)
  74. {
  75. Debug.Log("切换弹夹后:" + System.BitConverter.ToString(bytes));
  76. if (bytes[1] == 0x00 )
  77. {
  78. smartBowHelper.InvokeOnBleDevice(BluetoothDeviceType.Pistol1, BluetoothDeviceStatus.MagazineSeparation);
  79. }
  80. else if(bytes[1] == 0x01) {
  81. smartBowHelper.InvokeOnBleDevice(BluetoothDeviceType.Pistol1, BluetoothDeviceStatus.MagazineLoading);
  82. }
  83. }
  84. }
  85. }