MoveComponent.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
  30. // 协程如果取消,将算出玩家的真实位置,赋值给玩家
  31. cancellationToken.Add(() =>
  32. {
  33. long timeNow = TimeHelper.ClientNow();
  34. if (timeNow - this.StartTime >= this.needTime)
  35. {
  36. unit.Position = this.Target;
  37. }
  38. else
  39. {
  40. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  41. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  42. }
  43. });
  44. while (true)
  45. {
  46. await timerComponent.WaitAsync(50, cancellationToken);
  47. long timeNow = TimeHelper.ClientNow();
  48. if (timeNow - this.StartTime >= this.needTime)
  49. {
  50. unit.Position = this.Target;
  51. break;
  52. }
  53. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  54. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  55. }
  56. }
  57. public async ETTask MoveToAsync(Vector3 target, ETCancellationToken cancellationToken)
  58. {
  59. // 新目标点离旧目标点太近,不设置新的
  60. if ((target - this.Target).sqrMagnitude < 0.01f)
  61. {
  62. return;
  63. }
  64. // 距离当前位置太近
  65. if ((this.GetParent<Unit>().Position - target).sqrMagnitude < 0.01f)
  66. {
  67. return;
  68. }
  69. this.Target = target;
  70. // 开启协程移动
  71. await StartMove(cancellationToken);
  72. }
  73. }
  74. }