Unity的AnimationCurve

转自:风宇冲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:一直为端点的值。
这里写图片描述

使用曲线:
在上面的脚本里,再添加几行代码,如下

1 using UnityEngine;
2 using System.Collections;
3 public class AnimationCurveTutor : MonoBehaviour {
4 public AnimationCurve anim;
5 public void Update()
6 {
7 transform.position = new Vector3(Time.time, anim.Evaluate(Time.time), 0);
8 }
9 }

运行后,物体会按曲线轨迹向右移动。

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。创建如下脚本,拖到任意物体运行即可。

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class CreateRuntime : MonoBehaviour {
 5     public AnimationCurve anim = new AnimationCurve();
 6     void Start() {
 7         Keyframe[] ks = new Keyframe[3];
 8         ks[0] = new Keyframe(0, 0);
 9         ks[0].inTangent = 0;
10         ks[1] = new Keyframe(4, 0);
11         ks[1].inTangent = 45;
12         ks[2] = new Keyframe(8, 0);
13         ks[2].inTangent = 90;
14         anim = new AnimationCurve(ks);
15     }
16     void Update() {
17         transform.position = new Vector3(Time.time, anim.Evaluate(Time.time), 0);
18     }
19 }

4.一些函数:

 1 public float Evaluate(float time)
 2 //获取当前time位置对应曲线上的value
 3 
 4 public int AddKey(Keyframe key)
 5 public int AddKey(float time, float value);
 6 //添加一个关键帧
 7 
 8 public int MoveKey(int index, Keyframe key)
 9 //移动一个关键帧到指定index处
10 
11 public void RemoveKey(int index);
12 //移除一个关键帧
13 
14 public void SmoothTangents(int index, float weight);
15 //平滑化指定索引的关键帧的in和out tangents,weight:The smoothing weight to apply to the keyframe’s tangents.
posted @ 2021-06-17 18:18  yassine  阅读(647)  评论(0编辑  收藏  举报