UnitPathComponentSystem.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using ETModel;
  4. using PF;
  5. namespace ETHotfix
  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.Entity.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 = Game.Scene.GetComponent<PathfindingComponent>();
  36. self.ABPath = ComponentFactory.Create<ETModel.ABPath, Vector3, Vector3>(unit.Position,
  37. new Vector3(target.x, target.y, target.z));
  38. pathfindingComponent.Search(self.ABPath);
  39. Log.Debug($"find result: {self.ABPath.Result.ListToString()}");
  40. self.CancellationTokenSource?.Cancel();
  41. self.CancellationTokenSource = new CancellationTokenSource();
  42. await self.MoveAsync(self.ABPath.Result);
  43. self.CancellationTokenSource.Dispose();
  44. self.CancellationTokenSource = null;
  45. }
  46. // 从index找接下来3个点,广播
  47. public static void BroadcastPath(this UnitPathComponent self, List<Vector3> path, int index, int offset)
  48. {
  49. Unit unit = self.GetParent<Unit>();
  50. Vector3 unitPos = unit.Position;
  51. M2C_PathfindingResult m2CPathfindingResult = new M2C_PathfindingResult();
  52. m2CPathfindingResult.X = unitPos.x;
  53. m2CPathfindingResult.Y = unitPos.y;
  54. m2CPathfindingResult.Z = unitPos.z;
  55. m2CPathfindingResult.Id = unit.Id;
  56. for (int i = 0; i < offset; ++i)
  57. {
  58. if (index + i >= self.ABPath.Result.Count)
  59. {
  60. break;
  61. }
  62. Vector3 v = self.ABPath.Result[index + i];
  63. m2CPathfindingResult.Xs.Add(v.x);
  64. m2CPathfindingResult.Ys.Add(v.y);
  65. m2CPathfindingResult.Zs.Add(v.z);
  66. }
  67. MessageHelper.Broadcast(m2CPathfindingResult);
  68. }
  69. }
  70. }