using System; using UnityEngine; public class MoveWithCurve : MonoBehaviour { [HideInInspector] public Vector3 EndPoint = new Vector3(); [Tooltip("x轴路线形状 起始和结尾 点值必须为0")] public AnimationCurve CurveX; [Tooltip("y轴路线形状 起始和结尾 点值必须为0")] public AnimationCurve CurveY; [Tooltip("z轴路线形状 起始和结尾 点值必须为0")] public AnimationCurve CurveZ; [Tooltip("y轴运动速度 结尾点值必须为1")] public AnimationCurve CurveSpeedY; [Tooltip("z轴运动速度 结尾点值必须为1")] public AnimationCurve CurveSpeedZ; [Tooltip("弧度缩放系数")] public float RadianScale = 1f; private float _duration = 0.5f; private float _elapsedTime = 0f; private Vector3 _startPoint = Vector3.zero; private bool _begin = false; private Action _effectOver; public void Begin(Action callBack) { _begin = true; _elapsedTime = 0; _effectOver = callBack; } void Start() { if (CurveX.length > 0) { float startTime = CurveX.keys[0].time; float endTime = CurveX.keys[CurveX.length - 1].time; _duration = endTime - startTime; } Update(); } public void SetStartPosition(Vector3 value) { _startPoint = value; } void Update() { if (!_begin) return; _elapsedTime += Time.deltaTime; if (_elapsedTime > _duration) { _elapsedTime = _duration; _begin = false; _effectOver?.Invoke(); } Vector3 l = Vector3.Lerp(_startPoint, EndPoint, _elapsedTime/_duration); float speedY = CurveSpeedY != null?CurveSpeedY.Evaluate(_elapsedTime):1; float speedZ = CurveSpeedZ != null?CurveSpeedZ.Evaluate(_elapsedTime):1; // 使用曲线计算位置 float newX = CurveX.Evaluate(_elapsedTime) * RadianScale + l.x; float newY = CurveY.Evaluate(_elapsedTime) * RadianScale * speedY + l.y; float newZ = CurveZ.Evaluate(_elapsedTime) * RadianScale * speedZ + l.z; transform.position = new Vector3(newX, newY, newZ); } }