在我们制作数学动画时,经常会遇到多个动作同时发生的情况。
比如:坐标轴出现的同时,标签也跟着浮现;或者一个图形变色的同时,它也在移动。
今天,我们就来聊聊 ManimCE 中同时执行多个动画的那些事儿。
实现多动画的三种方法
方法一:使用 add() 方法(最简单直接)
这是最基础的方法,适合初学者理解。它的原理是把多个动画添加到场景中,让它们同时开始播放。
from manim import *
class SimpleMultiAnimation(Scene):
def construct(self):
# 创建两个图形
circle = Circle(color=BLUE).shift(LEFT * 2)
square = Square(color=RED).shift(RIGHT * 2)
# 添加图形到场景
self.add(circle, square)
self.wait(0.5)
# 同时执行多个动画
self.play(circle.animate.shift(UP * 2), square.animate.shift(DOWN * 2))
self.wait()
运行效果:蓝色圆向上移动的同时,红色正方形向下移动。
方法二:使用 AnimationGroup(适合组织相关动画)
当你有多个动画需要作为一个整体来控制时,AnimationGroup 是个很好的选择。
class AnimationGroupExample(Scene):
def construct(self):
# 创建三个点
dots = VGroup(*[Dot(radius=0.1) for _ in range(3)])
dots.arrange(RIGHT, buff=1)
# 为每个点创建不同的动画
animations = [
dots[0].animate.shift(UP*2).set_color(YELLOW),
dots[1].animate.shift(DOWN*2).set_color(GREEN),
dots[2].animate.shift(LEFT*2).set_color(RED)
]
# 使用AnimationGroup同时播放
self.play(AnimationGroup(*animations))
self.wait()
方法三:使用 LaggedStart 和 Succession(进阶控制)
如果想要更精细的控制,比如让动画依次开始但部分重叠,可以使用这些高级类:
class LaggedStartExample(Scene):
def construct(self):
squares = VGroup(*[Square(side_length=1) for _ in range(4)])
squares.arrange(RIGHT, buff=0.5)
# 动画依次开始,但会重叠播放
self.play(
LaggedStart(
*[
s.animate.rotate(PI).set_color(random_bright_color())
for s in squares
],
lag_ratio=0.3 # 每个动画之间的延迟时间比例
),
run_time=3,
)
self.wait()
同时执行不同速率的动画
在实际制作动画时,我们经常需要让不同的动画以不同的速度进行。
比如,一个图形快速移动,另一个缓慢旋转。
这时我们可以通过ApplyMethod方法,精确控制每个动画的运动曲线:
class RateFunctionsExample(Scene):
def construct(self):
# 创建三个物体
dot1 = Dot(color=RED, radius=0.2).shift(LEFT * 3 + UP * 2)
dot2 = Dot(color=GREEN, radius=0.2).shift(LEFT * 3)
dot3 = Dot(color=BLUE, radius=0.2).shift(LEFT * 3 + DOWN * 2)
self.add(dot1, dot2, dot3)
anim1 = ApplyMethod(dot1.shift, RIGHT * 6, rate_func=linear) # 匀速
anim2 = ApplyMethod(
dot2.shift, RIGHT * 6, rate_func=rate_functions.ease_out_quad
) # 先快后慢
anim3 = ApplyMethod(
dot3.shift, RIGHT * 6, rate_func=rate_functions.ease_in_quad
) # 先慢后快
# 使用不同的速率函数
self.play(
anim1,
anim2,
anim3,
run_time=3,
)
self.wait()
常见问题
Q:为什么我的动画没有同时执行?
A:检查是否在 play() 方法中正确使用了逗号分隔多个动画,而不是分号。
Q:如何让动画精确地在同一时刻结束?
A:设置相同的 run_time 参数即可。
Q:不同速率的动画如何同步?
A:使用 rate_funcs 参数为每个动画指定不同的速率函数。
总结
掌握同时执行多个动画的技巧,能让你的数学动画更加生动和专业。
从简单的 add() 方法到复杂的速率函数组合,ManimCE提供了丰富的工具来满足各种需求。
多动手练习这些例子,相信你很快就能制作出专业级别的数学动画!