1. 程式人生 > >Unity3d AnimationCurve 運動物體 AnimationCurve移動物體

Unity3d AnimationCurve 運動物體 AnimationCurve移動物體

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimCuveMove : MonoBehaviour
{
    public AnimationCurve x_offsetCurve;
    public AnimationCurve y_offsetCurve;


    public float curStartTimePoint;  ///當前開始的時間
	public float curRuningTime; ///當前執行的時間
	public float totalRuningTime;///總執行的時間

    public Vector3 initPos;

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            ReSet();
        }
        curRuningTime = RealTime.time - curStartTimePoint;
        if (curRuningTime > totalRuningTime)
        {
            return;
        }
        else
        {
            SampleCurve(); ///插值運動軌跡
		}
    }


    float CurveTotalRuningTime(AnimationCurve ac)
    {
        return ac.keys[ac.keys.Length - 1].time;
    }

    private void Awake()
    {
        initPos = transform.position;
    }

    void ReSet()
    {
        transform.position = initPos;
        curStartTimePoint = RealTime.time;
        curRuningTime = 0f;
        //多條曲線存在時,選擇時間最長那條的曲線的時間
        totalRuningTime = Mathf.Max(CurveTotalRuningTime(x_offsetCurve), CurveTotalRuningTime(y_offsetCurve));
    }


    float x_offset;
    float y_offset;

    /// <summary>
    /// 插值運動軌跡
    /// </summary>
    void SampleCurve()
    {
        x_offset = x_offsetCurve.Evaluate(curRuningTime);
        y_offset = y_offsetCurve.Evaluate(curRuningTime);
        transform.position += new Vector3(x_offset, y_offset, 0);
    }
}