MoveComponent.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 : Entity
  15. {
  16. public Vector3 Target;
  17. // 开启移动协程的时间
  18. public long StartTime;
  19. // 开启移动协程的Unit的位置
  20. public Vector3 StartPos;
  21. public long needTime;
  22. public ETTaskCompletionSource moveTcs;
  23. public void Update()
  24. {
  25. if (this.moveTcs == null)
  26. {
  27. return;
  28. }
  29. Unit unit = this.GetParent<Unit>();
  30. long timeNow = TimeHelper.Now();
  31. if (timeNow - this.StartTime >= this.needTime)
  32. {
  33. unit.Position = this.Target;
  34. ETTaskCompletionSource tcs = this.moveTcs;
  35. this.moveTcs = null;
  36. tcs.SetResult();
  37. return;
  38. }
  39. float amount = (timeNow - this.StartTime) * 1f / this.needTime;
  40. unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
  41. }
  42. public ETTask MoveToAsync(Vector3 target, float speedValue, CancellationToken cancellationToken)
  43. {
  44. Unit unit = this.GetParent<Unit>();
  45. if ((target - this.Target).magnitude < 0.1f)
  46. {
  47. return ETTask.CompletedTask;
  48. }
  49. this.Target = target;
  50. this.StartPos = unit.Position;
  51. this.StartTime = TimeHelper.Now();
  52. float distance = (this.Target - this.StartPos).magnitude;
  53. if (Math.Abs(distance) < 0.1f)
  54. {
  55. return ETTask.CompletedTask;
  56. }
  57. this.needTime = (long)(distance / speedValue * 1000);
  58. this.moveTcs = new ETTaskCompletionSource();
  59. cancellationToken.Register(() =>
  60. {
  61. this.moveTcs = null;
  62. });
  63. return this.moveTcs.Task;
  64. }
  65. }
  66. }