ShootCheck.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using ArduinoBluetoothAPI;
  5. using BestHTTP.WebSocket;
  6. public class ShootCheck : MonoBehaviour
  7. {
  8. [SerializeField] Text text;
  9. CMD cmd = new CMD();
  10. bool locked = false;
  11. float maxAcc = 0;
  12. public float shootSpeed;
  13. public static ShootCheck ins;
  14. void Start()
  15. {
  16. ins = this;
  17. BluetoothDispatcher.shoot = OnDataReceived;
  18. }
  19. public void OnBluetoothReady(BluetoothShoot bluetoothShoot) {
  20. bluetoothShoot.WriteData(JsonUtility.ToJson(cmd).Replace("\"", ""));
  21. }
  22. public void OnDataReceived(byte[] bytes) {
  23. if (bytes.Length == 2)
  24. {
  25. DeviceBatteryView.ins.RenderBattery(2, bytes[0]);
  26. return;
  27. }
  28. for (int i = 0; i < (bytes.Length-2)/6; i++)
  29. {
  30. float acc = ToAcceleratedSpeed(bytes[i * 6 + 5], bytes[i * 6 + 6]);
  31. if (ins.check(acc) && ArmBow.ins)
  32. {
  33. ArmBow.ins.ADS_fire();
  34. }
  35. }
  36. }
  37. float ToAcceleratedSpeed(byte b1, byte b2)
  38. {
  39. int value = TwoByteToInt(b1, b2);
  40. return (float)value / 32768 * LoginMgr.myUserInfo.deviceAccValue;
  41. }
  42. int TwoByteToInt(byte b1, byte b2)
  43. {
  44. ushort twoByte = (ushort)(b1 * 256 + b2);
  45. short shortNum = (short)twoByte;
  46. return (int)shortNum;
  47. }
  48. bool check(float acc)
  49. {
  50. DebugLine.show(acc); //这个不需要注释,静态函数内置判断
  51. if (locked)
  52. {
  53. return false;
  54. }
  55. if (acc > cmd.getAcc() && acc > maxAcc)
  56. {
  57. maxAcc = acc;
  58. return false;
  59. }
  60. else if (acc < cmd.getAcc() && maxAcc != 0) {
  61. shootSpeed = maxAcc;
  62. // Log("最大加速度:" + maxAcc);
  63. maxAcc = 0;
  64. Dolock();
  65. Invoke("Unlock", 1.8f);
  66. return true;
  67. }
  68. return false;
  69. }
  70. void Dolock()
  71. {
  72. locked = true;
  73. }
  74. void Unlock()
  75. {
  76. locked = false;
  77. }
  78. void Log(string text)
  79. {
  80. if (this.text)
  81. {
  82. this.text.text = text;
  83. } else {
  84. Debug.Log(text);
  85. }
  86. }
  87. }
  88. [Serializable]
  89. class CMD {
  90. // public string ax = "y";
  91. // public int a = 6000;
  92. // public int r = 2;
  93. public string a = "y";
  94. public int a1 = 3;
  95. public int a2 = -3;
  96. public int r = 2;
  97. public float getAcc() {
  98. return a1;
  99. }
  100. }