UnitPathComponentSystem.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using PF;
  4. using UnityEngine;
  5. namespace ET
  6. {
  7. public static class UnitPathComponentHelper
  8. {
  9. public static async ETTask MoveAsync(this UnitPathComponent self, List<Vector3> path)
  10. {
  11. if (path.Count == 0)
  12. {
  13. return;
  14. }
  15. // 第一个点是unit的当前位置,所以不用发送
  16. for (int i = 1; i < path.Count; ++i)
  17. {
  18. // 每移动3个点发送下3个点给客户端
  19. if (i % 3 == 1)
  20. {
  21. self.BroadcastPath(path, i, 3);
  22. }
  23. Vector3 v3 = path[i];
  24. await self.Parent.GetComponent<MoveComponent>().MoveToAsync(v3, self.CancellationTokenSource.Token);
  25. }
  26. }
  27. public static async ETVoid MoveTo(this UnitPathComponent self, Vector3 target)
  28. {
  29. if ((self.Target - target).magnitude < 0.1f)
  30. {
  31. return;
  32. }
  33. self.Target = target;
  34. Unit unit = self.GetParent<Unit>();
  35. PathfindingComponent pathfindingComponent = self.Domain.GetComponent<PathfindingComponent>();
  36. self.ABPath = EntityFactory.Create<ABPathWrap, Vector3, Vector3>(self.Domain, unit.Position, new Vector3(target.x, target.y, target.z));
  37. pathfindingComponent.Search(self.ABPath);
  38. Log.Debug($"find result: {self.ABPath.Result.ListToString()}");
  39. self.CancellationTokenSource?.Cancel();
  40. self.CancellationTokenSource = EntityFactory.Create<ETCancellationTokenSource>(self.Domain);
  41. await self.MoveAsync(self.ABPath.Result);
  42. self.CancellationTokenSource.Dispose();
  43. self.CancellationTokenSource = null;
  44. }
  45. // 从index找接下来3个点,广播
  46. public static void BroadcastPath(this UnitPathComponent self, List<Vector3> path, int index, int offset)
  47. {
  48. Unit unit = self.GetParent<Unit>();
  49. Vector3 unitPos = unit.Position;
  50. M2C_PathfindingResult m2CPathfindingResult = new M2C_PathfindingResult();
  51. m2CPathfindingResult.X = unitPos.x;
  52. m2CPathfindingResult.Y = unitPos.y;
  53. m2CPathfindingResult.Z = unitPos.z;
  54. m2CPathfindingResult.Id = unit.Id;
  55. for (int i = 0; i < offset; ++i)
  56. {
  57. if (index + i >= self.ABPath.Result.Count)
  58. {
  59. break;
  60. }
  61. Vector3 v = self.ABPath.Result[index + i];
  62. m2CPathfindingResult.Xs.Add(v.x);
  63. m2CPathfindingResult.Ys.Add(v.y);
  64. m2CPathfindingResult.Zs.Add(v.z);
  65. }
  66. MessageHelper.Broadcast(unit, m2CPathfindingResult);
  67. }
  68. }
  69. }