把对象摆到合适位置,是写场景时用得最多的操作。官方示例把同一个圆、方、三角用三种方式各排一遍:绝对定位、相对定位、以及按边对齐。三者名字相近,语义差别很大,混用最常见的结果就是图形重叠。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from manim import *
import numpy as np
class MobjectPlacement(Scene):
def construct(self):
circle = Circle()
square = Square()
triangle = Triangle()
# place the circle two units left from the origin
circle.move_to(LEFT * 2)
# place the square to the left of the circle
square.next_to(circle, LEFT)
# align the left border of the triangle to the left border of the circle
triangle.align_to(circle, LEFT)
self.play(*[FadeIn(_o) for _o in [circle, square, triangle]], run_time=1.0)
self.wait(1)
self.wait(3.60)

演示视频

下载 Python 脚本

要点

  • move_to(LEFT * 2) 是绝对坐标,相对 ORIGIN 计算
  • next_to(circle, LEFT) 是相对定位,以另一个对象为参照并自动留出间距
  • align_to() 对齐的是「边」不是「中心」,align_to(circle, LEFT) 让两者左边界对齐

代码来源:Manim Community 官方 Manim’s building blocks 示例 MobjectPlacement,已在 Manim CE 0.20.1 实跑验证并生成上方视频。