| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using ArduinoBluetoothAPI;
- using BestHTTP.WebSocket;
- public class ShootCheck : MonoBehaviour
- {
- [SerializeField] Text text;
- CMD cmd = new CMD();
- bool locked = false;
- float maxAcc = 0;
- Queue<float> keyAccList = new Queue<float>();
- public float shootSpeed;
- public static ShootCheck ins;
- void Start()
- {
- ins = this;
- BluetoothDispatcher.shoot = OnDataReceived;
- }
- public void OnBluetoothReady(BluetoothShoot bluetoothShoot) {
- bluetoothShoot.WriteData(JsonUtility.ToJson(cmd).Replace("\"", ""));
- }
- public void OnDataReceived(byte[] bytes) {
- if (bytes.Length == 2)
- {
- DeviceBatteryView.ins.RenderBattery(2, bytes[0]);
- return;
- }
- for (int i = 0; i < (bytes.Length-2)/6; i++)
- {
- float acc = ToAcceleratedSpeed(bytes[i * 6 + 5], bytes[i * 6 + 6]);
- if (ins.check(acc) && ArmBow.ins)
- {
- ArmBow.ins.ADS_fire();
- }
- }
- }
- float ToAcceleratedSpeed(byte b1, byte b2)
- {
- int value = TwoByteToInt(b1, b2);
- return (float)value / 32768 * LoginMgr.myUserInfo.deviceAccValue;
- }
-
- int TwoByteToInt(byte b1, byte b2)
- {
- ushort twoByte = (ushort)(b1 * 256 + b2);
- short shortNum = (short)twoByte;
- return (int)shortNum;
- }
- bool check(float acc)
- {
- DebugLine.show(acc); //这个不需要注释,静态函数内置判断
- if (locked)
- {
- return false;
- }
- if (acc > cmd.getAcc())
- {
- if (acc > maxAcc)
- {
- maxAcc = acc;
- }
- keyAccList.Enqueue(acc);
- return false;
- }
- else if (acc < cmd.getAcc() && maxAcc != 0) {
- //积分求初速度
- shootSpeed = 0;
- float lasKeytAcc = 0;
- int keyAccIndex = 0;
- foreach (var keyAcc in keyAccList)
- {
- if (keyAccIndex > 0)
- {
- shootSpeed += keyAcc * 0.002f;
- shootSpeed -= (keyAcc - lasKeytAcc) * 0.002f / 2;
- }
- lasKeytAcc = keyAcc;
- keyAccIndex++;
- }
- //加速度acc的单位是g,最后需要乘上
- shootSpeed *= 9.80665f;
- //积分出来的值还是太小,需要一个倍率
- shootSpeed *= 10;
- Debug.LogWarning("初速度: " + shootSpeed + " 帧数: " + keyAccList.Count);
- //本轮计算结束
- keyAccList.Clear();
- maxAcc = 0;
- Dolock();
- Invoke("Unlock", 1.8f);
- return true;
- }
- return false;
- }
- void Dolock()
- {
- locked = true;
- }
- void Unlock()
- {
- locked = false;
- }
-
- void Log(string text)
- {
- if (this.text)
- {
- this.text.text = text;
- } else {
- Debug.Log(text);
- }
- }
- }
- [Serializable]
- class CMD {
- // public string ax = "y";
- // public int a = 6000;
- // public int r = 2;
- public string a = "y";
- public int a1 = 3;
- public int a2 = -3;
- public int r = 2;
- public float getAcc() {
- return a1;
- }
- }
|