不用 self.play(Rotate(...)),也能让对象一直转:给对象挂一个按 dt 累加的 updater。示例让黄线先正转 2 秒,再换一个 updater 反转 2 秒,演示 updater 的挂载与摘除。

完整代码

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
36
37
38
39
40
41
from manim import *
class RotationUpdater(Scene):
"""官方示例 RotationUpdater:给对象挂按 dt 累加的 updater,实现每帧持续旋转。
白线静止作参照,黄线先正转 2 秒再反转 2 秒,最后摘除 updater 停住。
rotate_about_origin 绕的是世界原点,所以线绕原点扫过一圈圆周轨迹。
"""
def construct(self):
title = Text("用 updater 让对象每帧持续旋转", font="STLiti", font_size=34).to_edge(UP)
subtitle = Text("rotate_about_origin(dt) 绕世界原点,不是绕自身中心",
font="STLiti", font_size=22, color=BLUE).next_to(title, DOWN, buff=0.18)
self.play(FadeIn(title), FadeIn(subtitle), run_time=0.7)
guide = Circle(radius=2.0, color=GREY_D, stroke_width=2)
origin = Dot(ORIGIN, radius=0.08, color=BLUE)
line_reference = Line(ORIGIN, LEFT * 2, stroke_width=6).set_color(WHITE)
line_moving = Line(ORIGIN, LEFT * 2, stroke_width=9).set_color(YELLOW)
legend = VGroup(
Text("白线:静止参照", font="STLiti", font_size=22, color=WHITE),
Text("黄线:挂 updater 持续旋转", font="STLiti", font_size=22, color=YELLOW),
Text("灰圆:线端点扫过的轨迹", font="STLiti", font_size=22, color=GREY_B),
).arrange(DOWN, aligned_edge=LEFT, buff=0.18).to_corner(UL).shift(DOWN * 1.9)
self.play(FadeIn(guide), FadeIn(origin), FadeIn(line_reference),
FadeIn(line_moving), FadeIn(legend), run_time=0.9)
def updater_forth(mobj, dt):
mobj.rotate_about_origin(dt)
def updater_back(mobj, dt):
mobj.rotate_about_origin(-dt)
stage1 = Text("正转:dt > 0,每帧累加", font="STLiti", font_size=24, color=YELLOW).to_edge(DOWN)
stage2 = Text("反转:换一个 updater,dt < 0", font="STLiti", font_size=24, color=GREEN).to_edge(DOWN)
stage3 = Text("摘除 updater:停在最后一帧", font="STLiti", font_size=24, color=BLUE).to_edge(DOWN)
self.add(stage1)
line_moving.add_updater(updater_forth)
self.wait(2.0)
self.remove(stage1)
self.add(stage2)
line_moving.remove_updater(updater_forth)
line_moving.add_updater(updater_back)
self.wait(2.0)
self.remove(stage2)
self.add(stage3)
line_moving.remove_updater(updater_back)
self.wait(1.8)

演示视频

下载 Python 脚本

要点

  • updater 回调的第二个参数 dt 是距上一帧的秒数,用它做与帧率无关的累加
  • rotate_about_origin(dt) 绕世界原点旋转,不是绕对象自身中心
  • remove_updater() 要传回同一个函数对象,lambda 写法容易摘不掉

代码来源:Manim Community 官方 Example Gallery 示例 RotationUpdater(MIT),已按本地 Manim CE 0.21.0 补齐参照图形、逐帧实跑验证并生成上方视频。