多个对象要一起动,先把它们装进 VGroup,之后对组的操作就等于对全体操作。示例把一组图形整体挪到目标位置,省掉逐个写动画的重复劳动。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from manim import *
import numpy as np
import sympy as sp
def head(cn, en):
t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
return VGroup(t, s)
def foot(cn):
return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
def bg_image(h=60, w=100, mode=0):
a = np.zeros((h, w, 4), dtype=np.uint8)
a[:, :, 3] = 255
if mode == 0:
a[:, :, 0] = np.linspace(10, 90, w, dtype=np.uint8)[None, :]
a[:, :, 2] = np.linspace(60, 160, w, dtype=np.uint8)[None, :]
elif mode == 1:
a[:, :, 1] = np.linspace(20, 110, h, dtype=np.uint8)[:, None]
a[:, :, 2] = np.linspace(40, 130, h, dtype=np.uint8)[:, None]
else:
a[:, :, 0] = 120
a[:, :, 1] = 70
a[:, :, 2] = np.linspace(30, 140, w, dtype=np.uint8)[None, :]
return ImageMobject(a)
class VGroupMove(Scene):
def construct(self):
self.add(head("多个对象一起移动", "VGroup"))
group = VGroup(Circle(radius=0.8, color=BLUE),
Square(side_length=1.5, color=YELLOW),
Triangle(color=RED).scale(0.9))
group.arrange(RIGHT, buff=0.9).shift(LEFT * 2.5)
self.play(FadeIn(group), run_time=1.2)
self.play(group.animate.shift(RIGHT * 4.5), run_time=2.2)
self.play(group.animate.rotate(PI / 6).scale(1.15), run_time=2.0)
self.play(FadeIn(foot("对 VGroup 的操作会作用在组内每一个对象上")), run_time=0.4)
self.wait(1.0)

演示视频

下载 Python 脚本

要点

  • VGroup(a, b, c) 保留子对象原有位置,只提供统一操作入口
  • 对 VGroup 做 shift / scale / set_color 会作用到所有子对象
  • 需要自动排列时用 arrange() 或 arrange_in_grid()

代码来源:Manim Community 官方 Example Gallery 示例 MovingGroupToDestination,已在 Manim CE 0.20.1 实跑验证并生成上方视频。