Manim,无变换的 ReplacementTransform

iro*_*est 2 python manim

我是马尼姆的新手。

如下例所示,

class scene_example(Scene):
    def construct(self):
        txt1 = Text("Text1")
        txt2 = Text("Change to this text without animation")

        self.play(FadeIn(txt1))
        self.play(ReplacementTransform(txt1, txt2))
Run Code Online (Sandbox Code Playgroud)

有什么方便的功能可以将txt1“替换”为txt2吗?(即,没有“变形”动画?)

class scene_example(Scene):
    def construct(self):
        txt1 = Text("Text1")
        txt2 = Text("Change to this text without animation")
        
        self.play(FadeIn(txt1))
        self.play(FadeOut(txt1), FadeIn(txt2) )
Run Code Online (Sandbox Code Playgroud)

这段代码将执行我想要的操作,但我觉得可能有像 ReplacemnetTransform 这样的函数来实现简单的“替换”动画。我尝试为 FadeIn 和 FadeOut 创建一个函数,但是这不起作用。

class q(Scene):
    def construct(self):
        def Replace(self, mObj1, mObj2):
            self.play(FadeIn(mObj1),FadeOut(mObj2))

        txt1 = "HI"
        txt2 = "HI2"

        self.play(FadeIn(txt1))
        Replace(txt1, txt2)
Run Code Online (Sandbox Code Playgroud)

小智 5

在您尝试编写的代码中:

class q(Scene):
    def construct(self):
        def Replace(self, mObj1, mObj2):
            self.play(FadeIn(mObj1),FadeOut(mObj2))

        txt1 = Text("HI")
        txt2 = Text("HI2")

        self.play(FadeIn(txt1))
        Replace(txt1, txt2)
Run Code Online (Sandbox Code Playgroud)

参数self不会Replace自动传递给函数。一种解决方案是替换 Replace(txt1, txt2)Replace(self, txt1, txt2).

Replace另一种选择是根本不使用 self 参数。代码

class q(Scene):
    def construct(self):
        def Replace(mObj1, mObj2):
            self.play(FadeIn(mObj1),FadeOut(mObj2))

        txt1 = Text("HI")
        txt2 = Text("HI2")

        self.play(FadeIn(txt1))
        Replace(txt1, txt2)
Run Code Online (Sandbox Code Playgroud)

应该也有效。在这种情况下,由于 python 中作用域的工作方式,self内部Replace指的是self传递给construct方法的参数。在前面的示例中, whereReplace有自己的self参数,该self参数屏蔽了传递给 的参数construct,而selfinside 则Replace引用了Replaces self。(默认情况下,除非在调用时给出任何值,否则它没有任何值Replace。事实上,当您尝试运行代码时,您可能会遇到类似于 的错误 TypeError: Replace() missing 1 required positional argument: 'mObj2'

Replace另一种可能性是在类内部q、方法外部定义construct

class q(Scene):
    def Replace(self, mObj1, mObj2):
        self.play(FadeIn(mObj1),FadeOut(mObj2))

    def construct(self):
        txt1 = Text("HI")
        txt2 = Text("HI2")

        self.play(FadeIn(txt1))
        self.Replace(txt1, txt2)
Run Code Online (Sandbox Code Playgroud)

此外,如果您只想用一些新文本替换初始文本,根本没有动画(甚至没有淡入和淡出),那么您可以使用

self.remove(txt1)
self.add(txt2)
Run Code Online (Sandbox Code Playgroud)

一个更复杂的选项是创建一个Animation用两个 MObject 实例化的自定义类,并淡出第一个 MObject,同时淡入第二个 MObject。

class FadingReplace(Animation):
  def __init__(self, obj1, obj2, ...):
    pass
#implementation left as an exercise for the reader
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

self.play(FadingReplace(txt1, txt2))
Run Code Online (Sandbox Code Playgroud)