MoveComponent.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using DG.Tweening;
  2. using System;
  3. using UnityEngine;
  4. using XGame.Framework.Components;
  5. using XGame.Framework.Map;
  6. namespace FL.Battle
  7. {
  8. public interface IMoveContext
  9. {
  10. Transform OwnerTr { get; }
  11. }
  12. /// <summary>
  13. /// 移动参数
  14. /// </summary>
  15. public struct MoveArgs
  16. {
  17. public Vector3 target;
  18. public float speed;
  19. public Ease ease;
  20. /// <summary>
  21. /// 延迟,单位: 毫秒
  22. /// </summary>
  23. public int delay;
  24. public Action callback;
  25. }
  26. public class MoveComponent : Component<IMoveContext>, IParallelTarget
  27. {
  28. public override int Order => 0;
  29. private Tween _tween;
  30. public Vector3 MoveDir { get; private set; }
  31. public bool IsMoving => _tween != null;
  32. Vector3 IParallelTarget.Position => Context.OwnerTr.position;
  33. public void MoveTo(MoveArgs args)
  34. {
  35. var position = Context.OwnerTr.localPosition;
  36. var duration = Mathf.Abs(args.target.y - position.y) / args.speed;
  37. MoveDir = Vector3.Normalize(args.target - position);
  38. var tween = Context.OwnerTr.DOLocalMoveY(args.target.y, duration);
  39. if (args.delay > 0)
  40. {
  41. tween.SetDelay(args.delay * 0.001f);
  42. }
  43. _tween = tween;
  44. var ease = args.ease == Ease.Unset ? Ease.Linear : args.ease;
  45. tween.SetEase(ease);
  46. tween.onComplete += () =>
  47. {
  48. _tween = null;
  49. MoveDir = Vector3.zero;
  50. args.callback?.Invoke();
  51. };
  52. }
  53. public void StopMove()
  54. {
  55. _tween?.Kill();
  56. _tween = null;
  57. MoveDir = Vector3.zero;
  58. }
  59. protected override void OnDispose()
  60. {
  61. StopMove();
  62. }
  63. }
  64. }