UnitPathComponentSystem.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using ETModel;
  4. using PF;
  5. using UnityEngine;
  6. namespace ETHotfix
  7. {
  8. public static class UnitPathComponentHelper
  9. {
  10. public static async ETTask 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.Parent.GetComponent<MoveComponent>().MoveToAsync(v3, self.CancellationTokenSource.Token);
  26. }
  27. }
  28. public static async ETVoid 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 = EntityFactory.Create<ABPathWrap, Vector3, Vector3>(self.Domain, unit.Position, 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 = EntityFactory.Create<ETCancellationTokenSource>(self.Domain);
  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(unit, m2CPathfindingResult);
  68. }
  69. }
  70. }