转自:风宇冲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.
新闻热点
疑难解答