MoveHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace ET
  4. {
  5. public static class MoveHelper
  6. {
  7. // 可以多次调用,多次调用的话会取消上一次的协程
  8. public static async ETTask FindPathMoveToAsync(this Unit unit, Vector3 target, ETCancellationToken cancellationToken = null)
  9. {
  10. float speed = unit.GetComponent<NumericComponent>().GetAsFloat(NumericType.Speed);
  11. if (speed < 0.001)
  12. {
  13. unit.SendStop(-1);
  14. return;
  15. }
  16. using (var list = ListComponent<Vector3>.Create())
  17. {
  18. unit.Domain.GetComponent<RecastPathComponent>().SearchPath(10001, unit.Position, target, list.List);
  19. List<Vector3> path = list.List;
  20. if (path.Count < 2)
  21. {
  22. unit.SendStop(-2);
  23. return;
  24. }
  25. // 广播寻路路径
  26. M2C_PathfindingResult m2CPathfindingResult = new M2C_PathfindingResult();
  27. m2CPathfindingResult.Id = unit.Id;
  28. for (int i = 0; i < list.List.Count; ++i)
  29. {
  30. Vector3 vector3 = list.List[i];
  31. m2CPathfindingResult.Xs.Add(vector3.x);
  32. m2CPathfindingResult.Ys.Add(vector3.y);
  33. m2CPathfindingResult.Zs.Add(vector3.z);
  34. }
  35. MessageHelper.Broadcast(unit, m2CPathfindingResult);
  36. bool ret = await unit.GetComponent<MoveComponent>().MoveToAsync(path, speed);
  37. if (ret) // 如果返回false,说明被其它移动取消了,这时候不需要通知客户端stop
  38. {
  39. unit.SendStop(0);
  40. }
  41. }
  42. }
  43. public static void SendStop(this Unit unit, int error)
  44. {
  45. MessageHelper.Broadcast(unit, new M2C_Stop()
  46. {
  47. Error = error,
  48. Id = unit.Id,
  49. X = unit.Position.x,
  50. Y = unit.Position.y,
  51. Z = unit.Position.z,
  52. A = unit.Rotation.x,
  53. B = unit.Rotation.y,
  54. C = unit.Rotation.z,
  55. W = unit.Rotation.w,
  56. });
  57. }
  58. }
  59. }