UnitPathComponentSystem.cs 2.9 KB

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