Skip to content

Instantly share code, notes, and snippets.

@abul4fia
Last active March 7, 2024 13:14
Show Gist options
  • Save abul4fia/5115dbb660ad4414cb5568d6870801c0 to your computer and use it in GitHub Desktop.
Save abul4fia/5115dbb660ad4414cb5568d6870801c0 to your computer and use it in GitHub Desktop.
Concise syntax for manim's ValueTrackers

Shortcuts for working with valuetrackers

  • Tired of typing v.get_value()?
    Type ~v instead thanks to this trick.

  • Tired of typing v.animate.set_value(n)?
    Type v@n instead thanks to this trick.

# Nifty trick to save lots of keystrokes if you use ValueTrackers (at the cost of readability?)
# I abused some python operators. @ (originally introduced for matrix multiplication)
# is almost never used for anything, so I repurposed it to set the value of a valuetracker
# in animated form, so x@0 is equivalent to x.animate.set_value(0)
# Also, I repurposed ~ (which is used for bitwise negation, not useful in valuetrackers)
# to access the value, so ~x is equivalent to x.get_value()
# The implementation is minimalistic
class VT(ValueTracker):
def __invert__(self):
return self.get_value()
def __matmul__(self, v):
return self.animate.set_value(v)
# Demo of use
class Test(Scene):
def construct(self):
# ValueTrackers are created as usual
x = VT(0)
y = VT(0)
# Use ~ to get their values
sq = always_redraw(lambda: Square().move_to([~x, ~y, 0]))
self.add(sq)
# Use @ to animate setting new values
self.play(x@4, y@2)
self.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment