UnitPathComponentSystem.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using UnityEngine;
  4. namespace ET
  5. {
  6. public static class UnitPathComponentHelper
  7. {
  8. public static async ETTask MoveAsync(this UnitPathComponent self, List<Vector3> path)
  9. {
  10. if (path.Count == 0)
  11. {
  12. return;
  13. }
  14. // 第一个点是unit的当前位置,所以不用发送
  15. for (int i = 1; i < path.Count; ++i)
  16. {
  17. // 每移动3个点发送下3个点给客户端
  18. if (i % 3 == 1)
  19. {
  20. self.BroadcastPath(path, i, 3);
  21. }
  22. Vector3 v3 = path[i];
  23. await self.Parent.GetComponent<MoveComponent>().MoveToAsync(v3, self.CancellationToken);
  24. }
  25. await ETTask.CompletedTask;
  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. RecastPathComponent recastPathComponent = self.Domain.GetComponent<RecastPathComponent>();
  36. RecastPath recastPath = EntityFactory.Create<RecastPath>((Entity)self.Domain);
  37. recastPath.StartPos = unit.Position;
  38. recastPath.EndPos = new Vector3(target.x, target.y, target.z);
  39. self.RecastPath = recastPath;
  40. //TODO 因为目前阶段只有一张地图,所以默认mapId为10001
  41. recastPathComponent.SearchPath(10001, self.RecastPath);
  42. //Log.Debug($"------start Pos: {self.RecastPath.StartPos}\n------end Pos: {self.RecastPath.EndPos}\n------find result: {self.RecastPath.Results.ListToString()}");
  43. self.CancellationToken?.Cancel();
  44. self.CancellationToken = new ETCancellationToken();
  45. await self.MoveAsync(self.RecastPath.Results);
  46. self.CancellationToken = null;
  47. }
  48. // 从index找接下来3个点,广播
  49. public static void BroadcastPath(this UnitPathComponent self, List<Vector3> path, int index, int offset)
  50. {
  51. Unit unit = self.GetParent<Unit>();
  52. Vector3 unitPos = unit.Position;
  53. M2C_PathfindingResult m2CPathfindingResult = new M2C_PathfindingResult();
  54. m2CPathfindingResult.X = unitPos.x;
  55. m2CPathfindingResult.Y = unitPos.y;
  56. m2CPathfindingResult.Z = unitPos.z;
  57. m2CPathfindingResult.Id = unit.Id;
  58. for (int i = 0; i < offset; ++i)
  59. {
  60. if (index + i >= self.RecastPath.Results.Count)
  61. {
  62. break;
  63. }
  64. Vector3 v = self.RecastPath.Results[index + i];
  65. m2CPathfindingResult.Xs.Add(v.x);
  66. m2CPathfindingResult.Ys.Add(v.y);
  67. m2CPathfindingResult.Zs.Add(v.z);
  68. }
  69. MessageHelper.Broadcast(self.GetParent<Unit>(), m2CPathfindingResult) ;
  70. }
  71. }
  72. }