Unity 中动态创建 Animation

本贴最后更新于 1899 天前,其中的信息可能已经沧海桑田

想系统性复习一下算法,写个可视化的算法学习工具,一开始打算用 JavaFx 写,但是 JavaFx 动画系统的资料太少,换 Unity。

主要步骤参考:https://blog.csdn.net/pigautumn/article/details/81781403

Animation 系统的关系是,1 个物体可以附加多个 Animation,1 个 Animation 可以附加多个 Clip,一个 Clip 可以附加多个 Curve,

每个 Curve 代表了这个物体的一个属性的变化曲线,比如 postion.x,物体位置在 x 方向上的变化。

因为 Unity 没有提供从 Clip 拿 Curve 的操作,而我又需要多次处理 Curve 增加关键帧。

测试了一下关于 Curve 的细节

同一个属性绑定到多个 Curve 上,只有最后一个会生效

        AnimationCurve curve1 = new AnimationCurve();
        curve1.AddKey(new Keyframe(1f, -100));
        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curve1);
       
        AnimationCurve curve2 = new AnimationCurve();
        curve2.AddKey(new Keyframe(0.5f, -200));
        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curve2);

curve1 和 curve2 都应用了 postion.x 属性,原本以为两个会合并,实际是只有 curve2 生效

修改 Curve 后需要再次 Set 才生效

        AnimationCurve curve1 = new AnimationCurve();
        curve1.AddKey(new Keyframe(1f, -100));
        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curve1);
        curve1.AddKey(new Keyframe(2f, -50));

上面代码中 2f, -50 虽然在 curve1 的基础上修改了,但没有生效。

正确使用方式

        AnimationCurve curve1 = new AnimationCurve();
        curve1.AddKey(new Keyframe(1f, -100));
        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curve1);
        curve1.AddKey(new Keyframe(2f, -50));
        clip.SetCurve("", typeof(RectTransform), "m_AnchoredPosition.x", curve1);

所以如果要从 Clip 或者 Curve,需要自己增加 Dictionary 保存 Clip 与 Curve 的关系。

KeyFrame 的单位

KeyFrame 的单位为秒,默认 1 秒 60 帧率,如果 time 设置为小数,比如 0.01,60*0.01=0.6 帧,四舍五入到第 1 帧。

imagepng

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1090 引用 • 3467 回帖 • 296 关注
  • 算法
    388 引用 • 254 回帖 • 21 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...