MoveHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace ET.Server
  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.01)
  12. {
  13. unit.SendStop(-1);
  14. return;
  15. }
  16. using var list = ListComponent<Vector3>.Create();
  17. unit.GetComponent<PathfindingComponent>().Find(unit.Position, target, list);
  18. List<Vector3> path = list;
  19. if (path.Count < 2)
  20. {
  21. unit.SendStop(0);
  22. return;
  23. }
  24. // 广播寻路路径
  25. M2C_PathfindingResult m2CPathfindingResult = new M2C_PathfindingResult();
  26. m2CPathfindingResult.Id = unit.Id;
  27. for (int i = 0; i < list.Count; ++i)
  28. {
  29. Vector3 vector3 = list[i];
  30. m2CPathfindingResult.Xs.Add(vector3.x);
  31. m2CPathfindingResult.Ys.Add(vector3.y);
  32. m2CPathfindingResult.Zs.Add(vector3.z);
  33. }
  34. MessageHelper.Broadcast(unit, m2CPathfindingResult);
  35. bool ret = await unit.GetComponent<MoveComponent>().MoveToAsync(path, speed);
  36. if (ret) // 如果返回false,说明被其它移动取消了,这时候不需要通知客户端stop
  37. {
  38. unit.SendStop(0);
  39. }
  40. }
  41. public static void Stop(this Unit unit, int error)
  42. {
  43. unit.GetComponent<MoveComponent>().Stop();
  44. unit.SendStop(error);
  45. }
  46. public static void SendStop(this Unit unit, int error)
  47. {
  48. MessageHelper.Broadcast(unit, new M2C_Stop()
  49. {
  50. Error = error,
  51. Id = unit.Id,
  52. X = unit.Position.x,
  53. Y = unit.Position.y,
  54. Z = unit.Position.z,
  55. A = unit.Rotation.x,
  56. B = unit.Rotation.y,
  57. C = unit.Rotation.z,
  58. W = unit.Rotation.w,
  59. });
  60. }
  61. }
  62. }