MoveComponent.cs 1.7 KB

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