UnitPathComponent.cs 1.5 KB

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