using System.Collections; using UnityEngine; // 通过 PlayTween() 触发动画 public class SimpleAxisTween : MonoBehaviour { public enum Axis { X, Y } // 轴向选项 [Header("Tween Settings")] public Axis axis = Axis.X; // 要缓动的轴 public float from = 0f; // 起始值 public float to = 100f; // 终点值 public float duration = 1f; // 总时长(秒)——外部可调 public AnimationCurve ease = AnimationCurve.EaseInOut(0, 0, 1, 1); private Coroutine tweenCo; private RectTransform rt; public void PlayTween() { if (tweenCo != null) StopCoroutine(tweenCo); tweenCo = StartCoroutine(TweenRoutine()); } private void Awake() { TryGetComponent(out rt); } private IEnumerator TweenRoutine() { float elapsed = 0f; SetPosition(from); while (elapsed < duration) { elapsed += Time.deltaTime; float t = Mathf.Clamp01(elapsed / duration); float easedT = ease.Evaluate(t); // 缓动插值 float current = Mathf.LerpUnclamped(from, to, easedT); SetPosition(current); yield return null; } // 强制落在终点 SetPosition(to); tweenCo = null; } private void SetPosition(float value) { if (rt != null) { Vector2 pos = rt.anchoredPosition; if (axis == Axis.X) pos.x = value; else pos.y = value; rt.anchoredPosition = pos; } else { Vector3 pos = transform.localPosition; if (axis == Axis.X) pos.x = value; else pos.y = value; transform.localPosition = pos; } } }