MoveComponent.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Threading;
  3. using UnityEngine;
  4. namespace ET
  5. {
  6. public class MoveComponentUpdateSystem : UpdateSystem<MoveComponent>
  7. {
  8. public override void Update(MoveComponent self)
  9. {
  10. self.Update();
  11. }
  12. }
  13. public class MoveComponent : Entity
  14. {
  15. public Vector3 Target;
  16. // 开启移动协程的时间
  17. public long StartTime;
  18. // 开启移动协程的Unit的位置
  19. public Vector3 StartPos;
  20. public long needTime;
  21. public ETTaskCompletionSource moveTcs;
  22. public void Update()
  23. {
  24. if (this.moveTcs == null)
  25. {
  26. return;
  27. }
  28. Unit unit = this.GetParent<Unit>();
  29. long timeNow = TimeHelper.Now();
  30. if (timeNow - this.StartTime >= this.needTime)
  31. {
  32. unit.Position = this.Target;
  33. ETTaskCompletionSource tcs = this.moveTcs;
  34. this.moveTcs = null;
  35. tcs.SetResult();
  36. return;
  37. }
  38. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  39. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  40. }
  41. public async ETTask MoveToAsync(Vector3 target, float speedValue, CancellationToken cancellationToken)
  42. {
  43. Unit unit = this.GetParent<Unit>();
  44. if ((target - this.Target).magnitude < 0.1f)
  45. {
  46. return;
  47. }
  48. this.Target = target;
  49. this.StartPos = unit.Position;
  50. this.StartTime = TimeHelper.Now();
  51. float distance = (this.Target - this.StartPos).magnitude;
  52. if (Math.Abs(distance) < 0.1f)
  53. {
  54. return;
  55. }
  56. this.needTime = (long)(distance / speedValue * 1000);
  57. this.moveTcs = new ETTaskCompletionSource();
  58. cancellationToken.Register(() =>
  59. {
  60. this.moveTcs = null;
  61. });
  62. await this.moveTcs.Task;
  63. }
  64. }
  65. }