UnitPathComponent.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using UnityEngine;
  4. namespace ET
  5. {
  6. public class UnitPathComponent : Entity
  7. {
  8. public List<Vector3> Path = new List<Vector3>();
  9. public Vector3 ServerPos;
  10. public CancellationTokenSource CancellationTokenSource;
  11. public async ETTask StartMove(CancellationToken cancellationToken)
  12. {
  13. for (int i = 0; i < this.Path.Count; ++i)
  14. {
  15. Vector3 v = this.Path[i];
  16. float speed = 5;
  17. if (i == 0)
  18. {
  19. // 矫正移动速度
  20. Vector3 clientPos = this.GetParent<Unit>().Position;
  21. float serverf = (ServerPos - v).magnitude;
  22. if (serverf > 0.1f)
  23. {
  24. float clientf = (clientPos - v).magnitude;
  25. speed = clientf / serverf * speed;
  26. }
  27. }
  28. this.Parent.GetComponent<TurnComponent>().Turn(v);
  29. await this.Parent.GetComponent<MoveComponent>().MoveToAsync(v, speed, cancellationToken);
  30. }
  31. }
  32. public async ETVoid StartMove(M2C_PathfindingResult message)
  33. {
  34. // 取消之前的移动协程
  35. this.CancellationTokenSource?.Cancel();
  36. this.CancellationTokenSource = new CancellationTokenSource();
  37. this.Path.Clear();
  38. for (int i = 0; i < message.Xs.Count; ++i)
  39. {
  40. this.Path.Add(new Vector3(message.Xs[i], message.Ys[i], message.Zs[i]));
  41. }
  42. ServerPos = new Vector3(message.X, message.Y, message.Z);
  43. await StartMove(this.CancellationTokenSource.Token);
  44. this.CancellationTokenSource.Dispose();
  45. this.CancellationTokenSource = null;
  46. }
  47. }
  48. }