SimpleLocationEstimation.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnscentedKalmanFilter;
  5. namespace ZIM
  6. {
  7. // 固定时间间隔下,预测位置轨迹
  8. public class SimpleLocationEstimation
  9. {
  10. //public bool Initialized;
  11. public Vector2 Predict;
  12. Vector2 LastLocation;
  13. Vector2 LastSpeed;
  14. Vector2 LastAcc;
  15. float AccChangeScale;
  16. List<Vector2> Locations;
  17. // 卡尔曼滤波作用于速度
  18. UKF filterx;
  19. UKF filtery;
  20. public SimpleLocationEstimation(float accChangeScale = 1)
  21. {
  22. Locations = new List<Vector2>();
  23. AccChangeScale = accChangeScale;
  24. filterx = new UKF();
  25. filtery = new UKF();
  26. }
  27. public Vector2 Update(Vector2 loc)
  28. {
  29. if (Locations == null)
  30. {
  31. var newSpeed = loc - LastLocation;
  32. var newAcc = newSpeed - LastSpeed;
  33. var accPredict = newAcc + (newAcc - LastAcc) * AccChangeScale;
  34. var speedPredict = newSpeed + accPredict;
  35. //if (speedPredict.x * newSpeed.x < 0)
  36. // speedPredict.x = 0;
  37. //if (speedPredict.y * newSpeed.y < 0)
  38. // speedPredict.y = 0;
  39. //var LocationPredict = loc + speedPredict;
  40. filterx.Update(new double[] { speedPredict.x });
  41. filtery.Update(new double[] { speedPredict.y });
  42. var LocationPredict = loc + new Vector2((float)filterx.getState()[0], (float)filtery.getState()[0]);
  43. LastSpeed = newSpeed;
  44. LastAcc = newAcc;
  45. LastLocation = loc;
  46. return Predict = LocationPredict;
  47. //return Predict = new Vector2((float)filterx.getState()[0], (float)filtery.getState()[0]);
  48. }
  49. if (Locations.Count < 2)
  50. {
  51. Locations.Add(loc);
  52. }
  53. else
  54. {
  55. Locations.Add(loc);
  56. var speed = new Vector2[] { Locations.ElementAt(1) - Locations.ElementAt(0), Locations.ElementAt(2) - Locations.ElementAt(1) };
  57. LastLocation = loc;
  58. LastSpeed = speed[1];
  59. LastAcc = speed[1] - speed[0];
  60. Locations = null;
  61. }
  62. return Predict = loc;
  63. }
  64. }
  65. }