| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- using System;
- using UnityEngine;
- using UnityEngine.UI;
- public class ShootCheck : MonoBehaviour
- {
- float[] accList = new float[30];
- int dataCount = 0;
- float gravity = 0;
- float maxAcc = 0;
- bool hasReachShootThreshold = false;
- bool locked = false;
- int hitCount = 0;
- public float shootSpeed;
- [SerializeField] Text text;
- public static ShootCheck ins;
- void Start()
- {
- ins = this;
- BluetoothClient.onDataReceived = (byte[] bytes) => {
- float ay = ToAcceleratedSpeed(bytes[6], bytes[7]);
- try
- {
- if (ShootCheck.ins.check(ay)) {
- if (ArmBow.ins != null) {
- ArmBow.ins.ADS_fire();
- }
- }
- }
- catch (Exception e)
- {
- Debug.Log(e.Message);
- }
- };
- }
- float ToAcceleratedSpeed(byte b1, byte b2)
- {
- int value = TwoByteToInt(b1, b2);
- return (float)value / 32768 * 16;
- }
-
- int TwoByteToInt(byte b1, byte b2)
- {
- ushort twoByte = (ushort)(b1 * 256 + b2);
- short shortNum = (short)twoByte;
- return (int)shortNum;
- }
- public bool check(float acc)
- {
- DebugLine.show(acc);
- for (int i = accList.Length - 1; i > 0; i--)
- {
- accList[i] = accList[i - 1];
- }
- accList[0] = acc;
- dataCount++;
- if (locked)
- {
- return false;
- }
- if (hasReachShootThreshold) {
- if (acc <= gravity) {
- hitCount++;
- Log("第" + hitCount + "次识别射箭,过滤正轴重力" + gravity.ToString("#0.000") + "后,所得最大加速度峰值" + (maxAcc - gravity).ToString("#0.000"));
- hasReachShootThreshold = false;
- maxAcc = 0;
- Dolock();
- Invoke("Unlock", 0.8f);
- return true;
- } else if (accList[1] > accList[0] && accList[1] > accList[2]) {
- if (accList[1] > maxAcc)
- {
- maxAcc = accList[1];
- }
- return false;
- }
- return false;
- }
- if (dataCount > 3)
- {
- float totalAcc = 0;
- for (int i = 0; i < 3; i++)
- {
- totalAcc += accList[i];
- }
- float rangeAcc = totalAcc / 3;
- float squareAcc = 0;
- for (int i = 0; i < 3; i++)
- {
- squareAcc += (float) Mathf.Pow(accList[i] - rangeAcc, 2);
- }
- squareAcc /= 3;
- if (squareAcc < 0.0003)
- {
- gravity = Mathf.Clamp(rangeAcc, -0.981f, 0.981f);
- }
- if (accList[1] - gravity > 3.3)
- {
- if (accList[1] > accList[0] && accList[1] > accList[2])
- {
- hasReachShootThreshold = true;
- maxAcc = accList[1];
- }
- }
- }
- return false;
- }
- void Dolock()
- {
- this.locked = true;
- }
- void Unlock()
- {
- this.locked = false;
- }
-
- void Log(string text)
- {
- if (this.text != null)
- {
- this.text.text = text;
- } else {
- Debug.Log(text);
- }
- }
- }
|