轉自:風宇沖Unity3D教程學院http://blog.sina.com.cn/s/blog_471132920101f8nv.html,本文有多處增刪減改,詳細內容請查看原文。
1.介紹 AnimationCurve是Unity3D里一個非常實用的功能。作用是編輯一條任意變化的曲線用在任何你想用在的地方。 如曲線地形,曲線軌跡等。也被用在了模型動畫播放時的碰撞盒縮放及重力調節。AnimationCurve 曲線的繪制方法和Ragespline中的物體輪廓勾勒的方法類似。
2.基本使用 物體腳本上添加變量: public AnimationCurve anim;
會得到: 
點擊區域進入曲線編輯界面: 
雙擊任意區域內地方,創建關鍵點。對關鍵點點鼠標郵件,則出如下界面: 
基本操作: 創建關鍵點:左鍵雙擊 刪除關鍵點: (1)鼠標移動至關鍵點上,右鍵->Delete Key。 (2)左鍵單擊關鍵點,然后按鍵盤上的delete
設置曲線類型:鼠標移動至關鍵點上,右鍵-> Auto:根據關鍵點自動設置曲線。 Free Smooth:統一設置入切線和出切線 Flat:入切線和出切線為水平 Broken:分別設置入切線和出切線
也可以選Left Tangent(入切線)或者Right Tangent(出切線)或者Both Tangents(兩切線)。 Free:自由曲線,與Broken效果基本一樣。 Linear:線性曲線 Constant:之前一直是上個點的值,然后瞬間變為這個點的值。
其中Auto最簡單,Broken調整空間最大。曲線效果以綠線為準。
編輯好一條曲線后,在曲線的左右兩端會有一個下拉菜單,點擊設置兩端各自重復的方式。 Loop:曲線循環 
Pingpong: 曲線和該曲線上下翻轉后的曲線循環 
Clamp:一直為端點的值。 
使用曲線: 在上面的腳本里,再添加幾行代碼,如下
using UnityEngine;using System.Collections;public class AnimationCurveTutor : MonoBehaviour {public AnimationCurve anim;public void Update(){transform.position = new Vector3(Time.time, anim.Evaluate(Time.time), 0);}}運行后,物體會按曲線軌跡向右移動。
3.腳本創建AnimationCurve AnimationCurve可以理解為2部分。(1)鍵序列(2)左右循環模式(又作左右包裹模式)
一:鍵序列 創建鍵序列:Keyframe[] ks = new Keyframe[3]; 曲線中加入鍵序列:AnimationCurve curve = new AnimationCurve(ks); 獲取曲線中的鍵序列:curve[index] 或者 curve.keys[index] 添加單鍵:curve.Addkey(time,value) 刪除單鍵:curve.RemoveKey(index)
二:左右循環 anim.PReWrapMode = WrapMode.Loop; anim.postWrapMode = WrapMode.Once;
三:鍵 Keyframe kf = new Keyframe(time,value); kf.inTangent = 45; kf.outTangent = 45;
用腳本動態實時創建AnimationCurve。創建如下腳本,拖到任意物體運行即可。
using UnityEngine;using System.Collections;public class CreateRuntime : MonoBehaviour { public AnimationCurve anim = new AnimationCurve(); void Start() { Keyframe[] ks = new Keyframe[3]; ks[0] = new Keyframe(0, 0); ks[0].inTangent = 0; ks[1] = new Keyframe(4, 0); ks[1].inTangent = 45; ks[2] = new Keyframe(8, 0); ks[2].inTangent = 90; anim = new AnimationCurve(ks); } void Update() { transform.position = new Vector3(Time.time, anim.Evaluate(Time.time), 0); }}4.一些函數: 1/ public float Evaluate(float time) 獲取當前time位置對應曲線上的value
2/ public int AddKey(Keyframe key) public int AddKey(float time, float value); 添加一個關鍵幀
3/ public int MoveKey(int index, Keyframe key) 移動一個關鍵幀到指定index處
4/ public void RemoveKey(int index); 移除一個關鍵幀
5/ public void SmoothTangents(int index, float weight); //平滑化指定索引的關鍵幀的in和out tangents,weight:The smoothing weight to apply to the keyframe’s tangents.
新聞熱點
疑難解答