如何在Manim中更新点的实时位置并同步更新点标签?
问题描述
目前点动画仅显示(x1|y1)、(x2|y2)和(x3|y3),如何让点的标签显示对应点的真实坐标(即使移动点之后)?
原始代码
from manim import * import math class Test2(Scene): def construct(self): # Mobject plane = NumberPlane().add_coordinates() dot1 = Dot([2, 2, 0],radius=0.1 ,color=RED) dot2 = Dot([-2, 2, 0],radius=0.1, color=YELLOW) dot3 = Dot([0, -1, 0],radius=0.1, color=GREEN) dot1label = Text("(x1|y1)", font_size=25).next_to(dot1, RIGHT) dot2label = Text("(x2|y2)", font_size=25).next_to(dot2, RIGHT) dot3label = Text("(x3|y3)", font_size=25).next_to(dot3, RIGHT) labels = VGroup(dot1label, dot2label, dot3label) dot1label.add_updater(lambda x: x.next_to(dot1, DOWN + RIGHT)) dot2label.add_updater(lambda x: x.next_to(dot2, DOWN + RIGHT)) dot3label.add_updater(lambda x: x.next_to(dot3, DOWN + RIGHT)) # script self.play(Create(plane)) self.wait(0.5) self.play(Create(dot1), Create(dot2), Create(dot3)) self.play(FadeIn(labels, shift=UP * 0.2)) self.wait(1) self.play(dot1.animate.shift([-1,-3,0])) self.play(dot2.animate.shift([-1,-2,0])) self.play(dot3.animate.shift([3,1,0])) self.wait(3)
解决方案
原始代码中的Text是静态文本,仅能跟随点移动位置,但内容不会更新。要实现动态显示坐标,需要给标签添加内容更新器,实时读取点的坐标并格式化显示。
修改后的代码如下:
from manim import * import math class Test2(Scene): def construct(self): # Mobject plane = NumberPlane().add_coordinates() dot1 = Dot([2, 2, 0], radius=0.1, color=RED) dot2 = Dot([-2, 2, 0], radius=0.1, color=YELLOW) dot3 = Dot([0, -1, 0], radius=0.1, color=GREEN) # 定义坐标格式化函数 def get_coord_text(dot): x = round(dot.get_x(), 1) y = round(dot.get_y(), 1) return f"({x}|{y})" # 初始化标签,显示初始坐标 dot1label = Text(get_coord_text(dot1), font_size=25).next_to(dot1, DOWN + RIGHT) dot2label = Text(get_coord_text(dot2), font_size=25).next_to(dot2, DOWN + RIGHT) dot3label = Text(get_coord_text(dot3), font_size=25).next_to(dot3, DOWN + RIGHT) labels = VGroup(dot1label, dot2label, dot3label) # 添加位置+内容双重更新器 dot1label.add_updater(lambda label: label.next_to(dot1, DOWN + RIGHT).set_text(get_coord_text(dot1))) dot2label.add_updater(lambda label: label.next_to(dot2, DOWN + RIGHT).set_text(get_coord_text(dot2))) dot3label.add_updater(lambda label: label.next_to(dot3, DOWN + RIGHT).set_text(get_coord_text(dot3))) # script self.play(Create(plane)) self.wait(0.5) self.play(Create(dot1), Create(dot2), Create(dot3)) self.play(FadeIn(labels, shift=UP * 0.2)) self.wait(1) self.play(dot1.animate.shift([-1,-3,0])) self.play(dot2.animate.shift([-1,-2,0])) self.play(dot3.animate.shift([3,1,0])) self.wait(3)
关键修改点
- 新增
get_coord_text函数,将点的坐标格式化为(x|y)字符串,用round保留1位小数避免数字过长 - 给每个标签的更新器增加
set_text(get_coord_text(dot))逻辑,实时更新文本内容 - 保留
next_to确保标签始终跟随对应点的位置
修改后,无论点如何移动,标签都会实时显示当前的坐标值。
内容的提问来源于stack exchange,提问作者Hütti
相关产品推荐
相关产品推荐

