Home > Back-end >  How to use Manim to animate a point moving on a number line?
How to use Manim to animate a point moving on a number line?

Time:04-26

I'd like to use Manim to animate the position of a parameter on a number line. I figured out how to animate the end position of the parameter as a line using ParametricFunction:

from manim import *
import numpy as np
import math

class line( Scene ):
    def construct( self ):

        tline = NumberLine(
            x_range=[ 0, 1 ],
            length=4,
            color=BLUE,
            include_numbers=False )

        t1 = ParametricFunction( lambda t: tline.number_to_point(np.sin(t * PI)),
                                 t_range=[0, 1],
                                 scaling=tline.scaling, color=YELLOW )

        self.play( DrawBorderThenFill( VGroup( tline ) ), run_time = 2 )
        self.play( AnimationGroup(Create(t1)), run_time = 6 )

This works okay for monotonically increasing values, but is no good if the end point doubles back on itself, as the animation becomes invisible at that stage.

Is there a way to change the line plot to animate a moving point instead of tracing out a line?

CodePudding user response:

If your parameter simply moves between certain fixed values, you could follow a simple approach as in this example in the documentation.

If you want more control over the exact way the marker moves across the number line, I'd recommend replicating something similar with a ValueTracker and the UpdateFromAlphaFunc animation, like this:

from manim import *

class Example(Scene):
    def construct(self):
        tline = NumberLine(
            x_range=[ 0, 1 ],
            length=4,
            color=BLUE,
            include_numbers=False )

        t_parameter = ValueTracker(0)
        t_marker = Dot(color=YELLOW).add_updater(
            lambda mob: mob.move_to(tline.number_to_point(t_parameter.get_value())),
        ).update()
        self.play( DrawBorderThenFill( VGroup( tline ) ), run_time = 2 )
        self.add(t_marker)
        self.play(
            UpdateFromAlphaFunc(
                t_parameter, 
                lambda mob, alpha: mob.set_value(np.sin(alpha * PI)),
                run_time=6
            )
        )
  • Related