MoveComponent.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Threading;
  3. using UnityEngine;
  4. namespace ET
  5. {
  6. public class MoveComponent: Entity
  7. {
  8. public Vector3 Target;
  9. // 开启移动协程的时间
  10. public long StartTime;
  11. // 开启移动协程的Unit的位置
  12. public Vector3 StartPos;
  13. public long needTime;
  14. // 当前的移动速度
  15. public float Speed = 5;
  16. // 开启协程移动,每100毫秒移动一次,并且协程取消的时候会计算玩家真实移动
  17. // 比方说玩家移动了2500毫秒,玩家有新的目标,这时旧的移动协程结束,将计算250毫秒移动的位置,而不是300毫秒移动的位置
  18. public async ETTask StartMove(ETCancellationToken cancellationToken)
  19. {
  20. Unit unit = this.GetParent<Unit>();
  21. this.StartPos = unit.Position;
  22. this.StartTime = TimeHelper.ClientNow();
  23. float distance = (this.Target - this.StartPos).magnitude;
  24. if (Math.Abs(distance) < 0.1f)
  25. {
  26. return;
  27. }
  28. this.needTime = (long)(distance / this.Speed * 1000);
  29. // 协程如果取消,将算出玩家的真实位置,赋值给玩家
  30. cancellationToken?.Add(() =>
  31. {
  32. long timeNow = TimeHelper.ClientNow();
  33. if (timeNow - this.StartTime >= this.needTime)
  34. {
  35. unit.Position = this.Target;
  36. }
  37. else
  38. {
  39. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  40. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  41. }
  42. });
  43. while (true)
  44. {
  45. //新版TimerComponent实现不同于5.0的TimerComponent,需要自己判断是取消还是自然结束,并且return,否则将不会取消任务,并可能会造成cancellationToken泄漏
  46. if (!await TimerComponent.Instance.WaitAsync(50, cancellationToken))
  47. {
  48. return;
  49. }
  50. long timeNow = TimeHelper.ClientNow();
  51. if (timeNow - this.StartTime >= this.needTime)
  52. {
  53. unit.Position = this.Target;
  54. break;
  55. }
  56. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  57. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  58. }
  59. }
  60. public async ETTask MoveToAsync(Vector3 target, ETCancellationToken cancellationToken)
  61. {
  62. // 新目标点离旧目标点太近,不设置新的
  63. if ((target - this.Target).sqrMagnitude < 0.01f)
  64. {
  65. return;
  66. }
  67. // 距离当前位置太近
  68. if ((this.GetParent<Unit>().Position - target).sqrMagnitude < 0.01f)
  69. {
  70. return;
  71. }
  72. this.Target = target;
  73. // 开启协程移动
  74. await StartMove(cancellationToken);
  75. }
  76. }
  77. }