0
# Advanced Animations
1
2
ManimGL provides sophisticated animation capabilities beyond basic transformations, including specialized animation techniques, transform matching systems, and advanced composition patterns for complex mathematical demonstrations and educational content.
3
4
## Capabilities
5
6
### Transform Matching Parts
7
8
Advanced object morphing that intelligently matches corresponding parts between objects for smooth, meaningful transformations.
9
10
```python { .api }
11
class TransformMatchingParts(AnimationGroup):
12
def __init__(
13
self,
14
mobject: Mobject,
15
target_mobject: Mobject,
16
transform_mismatches: bool = False,
17
fade_transform_mismatches: bool = False,
18
key_map: dict | None = None,
19
**kwargs
20
):
21
"""
22
Transform objects by matching corresponding parts.
23
24
Parameters:
25
- mobject: Source object to transform
26
- target_mobject: Target object to transform into
27
- transform_mismatches: Transform unmatched parts
28
- fade_transform_mismatches: Fade unmatched parts during transform
29
- key_map: Manual mapping of parts between objects
30
"""
31
32
class TransformMatchingTex(TransformMatchingParts):
33
def __init__(
34
self,
35
mobject: Mobject,
36
target_mobject: Mobject,
37
key_map: dict | None = None,
38
**kwargs
39
):
40
"""
41
Specialized transform for LaTeX expressions with intelligent symbol matching.
42
43
Parameters:
44
- mobject: Source LaTeX expression
45
- target_mobject: Target LaTeX expression
46
- key_map: Manual mapping of LaTeX symbols
47
"""
48
49
class TransformMatchingShapes(TransformMatchingParts):
50
def __init__(
51
self,
52
mobject: Mobject,
53
target_mobject: Mobject,
54
transform_mismatches: bool = True,
55
**kwargs
56
):
57
"""
58
Transform shapes by matching geometric components.
59
60
Parameters:
61
- mobject: Source shape
62
- target_mobject: Target shape
63
- transform_mismatches: Handle unmatched components
64
"""
65
```
66
67
### Specialized Animation Effects
68
69
Advanced animation effects for specific use cases and visual impact in mathematical demonstrations.
70
71
```python { .api }
72
class Homotopy(Animation):
73
def __init__(
74
self,
75
homotopy_function: Callable,
76
mobject: Mobject,
77
**kwargs
78
):
79
"""
80
Apply continuous deformation via homotopy function.
81
82
Parameters:
83
- homotopy_function: Function (x, y, z, t) -> (x', y', z')
84
- mobject: Object to deform
85
"""
86
87
class PhaseFlow(Animation):
88
def __init__(
89
self,
90
function: Callable,
91
mobject: Mobject,
92
**kwargs
93
):
94
"""
95
Move object along vector field flow.
96
97
Parameters:
98
- function: Vector field function
99
- mobject: Object to move along flow
100
"""
101
102
class ComplexHomotopy(Homotopy):
103
def __init__(
104
self,
105
complex_homotopy: Callable,
106
mobject: Mobject,
107
**kwargs
108
):
109
"""
110
Apply complex function transformations over time.
111
112
Parameters:
113
- complex_homotopy: Complex function (z, t) -> z'
114
- mobject: Object to transform
115
"""
116
```
117
118
### Animation Composition Patterns
119
120
Advanced patterns for combining and sequencing animations with sophisticated timing and coordination.
121
122
```python { .api }
123
class AnimationGroup(Animation):
124
def __init__(
125
self,
126
*animations: Animation,
127
lag_ratio: float = 0,
128
run_time: float | None = None,
129
**kwargs
130
):
131
"""
132
Group animations with staggered timing.
133
134
Parameters:
135
- animations: List of animations to group
136
- lag_ratio: Delay between animation starts (0-1)
137
- run_time: Total duration (max of animations if None)
138
"""
139
140
class Succession(AnimationGroup):
141
def __init__(self, *animations: Animation, **kwargs):
142
"""
143
Play animations in sequence (lag_ratio=1).
144
145
Parameters:
146
- animations: Animations to play sequentially
147
"""
148
149
class LaggedStart(AnimationGroup):
150
def __init__(
151
self,
152
*animations: Animation,
153
lag_ratio: float = DEFAULT_LAGGED_START_LAG_RATIO,
154
**kwargs
155
):
156
"""
157
Start animations with uniform lag.
158
159
Parameters:
160
- animations: Animations to stagger
161
- lag_ratio: Delay ratio between starts
162
"""
163
164
class LaggedStartMap(LaggedStart):
165
def __init__(
166
self,
167
AnimationClass: type,
168
mobject: Mobject,
169
arg_creator: Callable | None = None,
170
**kwargs
171
):
172
"""
173
Apply animation class to submobjects with lag.
174
175
Parameters:
176
- AnimationClass: Animation class to apply
177
- mobject: Object with submobjects
178
- arg_creator: Function to create arguments for each submobject
179
"""
180
```
181
182
### Update Animations
183
184
Dynamic animations that continuously update based on functions or external state.
185
186
```python { .api }
187
class UpdateFromFunc(Animation):
188
def __init__(
189
self,
190
mobject: Mobject,
191
update_function: Callable,
192
**kwargs
193
):
194
"""
195
Continuously update mobject via function.
196
197
Parameters:
198
- mobject: Object to update
199
- update_function: Function taking (mobject, dt) or (mobject, alpha)
200
"""
201
202
class UpdateFromAlphaFunc(UpdateFromFunc):
203
def __init__(
204
self,
205
mobject: Mobject,
206
update_function: Callable,
207
**kwargs
208
):
209
"""
210
Update mobject based on animation progress (alpha 0-1).
211
212
Parameters:
213
- mobject: Object to update
214
- update_function: Function taking (mobject, alpha)
215
"""
216
217
class MaintainPositionRelativeTo(Animation):
218
def __init__(
219
self,
220
mobject: Mobject,
221
tracked_mobject: Mobject,
222
**kwargs
223
):
224
"""
225
Keep mobject positioned relative to another mobject.
226
227
Parameters:
228
- mobject: Object to maintain position
229
- tracked_mobject: Object to track
230
"""
231
```
232
233
### Specialized Mathematical Animations
234
235
Domain-specific animations for mathematical concepts and demonstrations.
236
237
```python { .api }
238
class CyclicReplace(Transform):
239
def __init__(self, *mobjects: Mobject, **kwargs):
240
"""
241
Cyclically replace mobjects in sequence.
242
243
Parameters:
244
- mobjects: Objects to cycle through
245
"""
246
247
class Swap(CyclicReplace):
248
def __init__(self, mobject1: Mobject, mobject2: Mobject, **kwargs):
249
"""
250
Swap positions of two mobjects.
251
252
Parameters:
253
- mobject1: First object
254
- mobject2: Second object
255
"""
256
257
class TransformFromCopy(Transform):
258
def __init__(
259
self,
260
mobject: Mobject,
261
target_mobject: Mobject,
262
**kwargs
263
):
264
"""
265
Transform copy of mobject, leaving original unchanged.
266
267
Parameters:
268
- mobject: Source object (remains unchanged)
269
- target_mobject: Target for transformation
270
"""
271
```
272
273
## Usage Examples
274
275
### Mathematical Expression Transformation
276
277
```python
278
from manimlib import *
279
280
class ExpressionTransform(Scene):
281
def construct(self):
282
# Start with a complex expression
283
expr1 = Tex(r"(x + y)^2")
284
expr2 = Tex(r"x^2 + 2xy + y^2")
285
286
expr1.scale(1.5)
287
expr2.scale(1.5)
288
289
self.play(Write(expr1))
290
self.wait()
291
292
# Use intelligent symbol matching
293
self.play(
294
TransformMatchingTex(expr1, expr2),
295
run_time=3
296
)
297
self.wait()
298
299
# Transform to factored form
300
expr3 = Tex(r"(x + y)(x + y)")
301
expr3.scale(1.5)
302
303
self.play(
304
TransformMatchingTex(expr2, expr3),
305
run_time=2
306
)
307
self.wait()
308
```
309
310
### Complex Function Visualization
311
312
```python
313
class ComplexTransformation(Scene):
314
def construct(self):
315
# Create a grid in the complex plane
316
grid = NumberPlane(
317
x_range=[-3, 3], y_range=[-3, 3],
318
background_line_style={"stroke_width": 1, "stroke_opacity": 0.5}
319
)
320
321
# Define complex transformation z -> z^2
322
def complex_func(z, t):
323
# Gradually apply z^2 transformation
324
return z * (1 + t * (z - 1))
325
326
self.add(grid)
327
328
# Apply complex homotopy
329
self.play(
330
ComplexHomotopy(complex_func, grid),
331
run_time=4
332
)
333
self.wait()
334
```
335
336
### Geometric Deformation
337
338
```python
339
class GeometricHomotopy(Scene):
340
def construct(self):
341
# Create a circle
342
circle = Circle(radius=2, color=BLUE, fill_opacity=0.3)
343
self.add(circle)
344
345
# Define homotopy: circle -> square
346
def circle_to_square(x, y, z, t):
347
# Interpolate between circular and square coordinates
348
r = np.sqrt(x*x + y*y)
349
if r == 0:
350
return np.array([x, y, z])
351
352
# Square coordinates
353
max_coord = max(abs(x), abs(y))
354
square_x = x * (max_coord / r) if r > 0 else x
355
square_y = y * (max_coord / r) if r > 0 else y
356
357
# Interpolate
358
new_x = x + t * (square_x - x)
359
new_y = y + t * (square_y - y)
360
361
return np.array([new_x, new_y, z])
362
363
self.play(
364
Homotopy(circle_to_square, circle),
365
run_time=3
366
)
367
self.wait()
368
```
369
370
### Coordinated Group Animations
371
372
```python
373
class CoordinatedAnimations(Scene):
374
def construct(self):
375
# Create a group of objects
376
dots = VGroup(*[
377
Dot(radius=0.1).move_to([i*0.5, 0, 0])
378
for i in range(-5, 6)
379
])
380
381
colors = [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE] * 2
382
383
self.add(dots)
384
385
# Animate with staggered timing
386
self.play(
387
LaggedStartMap(
388
lambda dot, color: dot.animate.set_color(color).scale(2),
389
dots,
390
lambda dot: {"color": colors[dots.submobjects.index(dot)]},
391
lag_ratio=0.1
392
),
393
run_time=3
394
)
395
396
# Coordinated movement
397
self.play(
398
LaggedStart(
399
*[dot.animate.shift(UP * 2) for dot in dots],
400
lag_ratio=0.05
401
),
402
run_time=2
403
)
404
405
# Return with different pattern
406
self.play(
407
AnimationGroup(
408
*[dot.animate.shift(DOWN * 2).scale(0.5) for dot in dots],
409
lag_ratio=0.8 # More staggered
410
),
411
run_time=3
412
)
413
```
414
415
### Dynamic Function Following
416
417
```python
418
class DynamicTracking(Scene):
419
def construct(self):
420
# Create axes and function
421
axes = Axes(x_range=[-3, 3], y_range=[-2, 2])
422
423
# Time-varying function
424
t_tracker = ValueTracker(0)
425
426
def get_func():
427
t = t_tracker.get_value()
428
return axes.plot(
429
lambda x: np.sin(x + t),
430
color=YELLOW
431
)
432
433
graph = get_func()
434
graph.add_updater(lambda g: g.become(get_func()))
435
436
# Dot that follows the function maximum
437
dot = Dot(color=RED)
438
439
def update_dot(d):
440
t = t_tracker.get_value()
441
max_x = -t % (2 * PI) - PI # Position of maximum
442
max_y = 1 # Maximum value of sine
443
d.move_to(axes.c2p(max_x, max_y))
444
445
dot.add_updater(update_dot)
446
447
self.add(axes, graph, dot)
448
449
# Animate time parameter
450
self.play(
451
t_tracker.animate.set_value(4 * PI),
452
run_time=8,
453
rate_func=linear
454
)
455
```
456
457
### Transform Matching with Custom Rules
458
459
```python
460
class CustomTransformMatching(Scene):
461
def construct(self):
462
# Create source and target expressions
463
source = VGroup(
464
Circle(radius=0.3, color=BLUE).shift(LEFT * 2),
465
Square(side_length=0.6, color=RED),
466
Triangle().scale(0.4).shift(RIGHT * 2).set_color(GREEN)
467
)
468
469
target = VGroup(
470
Square(side_length=0.6, color=BLUE).shift(LEFT * 2),
471
Triangle().scale(0.4).set_color(RED),
472
Circle(radius=0.3, color=GREEN).shift(RIGHT * 2)
473
)
474
475
self.add(source)
476
self.wait()
477
478
# Custom key mapping for transform
479
key_map = {
480
source[0]: target[2], # Circle -> Circle (different position)
481
source[1]: target[0], # Square -> Square (different position)
482
source[2]: target[1] # Triangle -> Triangle (different position)
483
}
484
485
self.play(
486
TransformMatchingParts(
487
source,
488
target,
489
key_map=key_map,
490
transform_mismatches=True
491
),
492
run_time=3
493
)
494
self.wait()
495
```
496
497
### Advanced Update Patterns
498
499
```python
500
class AdvancedUpdates(Scene):
501
def construct(self):
502
# Create objects with complex interdependencies
503
center_dot = Dot(color=YELLOW)
504
505
# Orbiting dots
506
orbit_dots = VGroup(*[
507
Dot(radius=0.05, color=BLUE).shift(RIGHT * (1 + 0.3 * i))
508
for i in range(5)
509
])
510
511
# Time tracker
512
time_tracker = ValueTracker(0)
513
514
# Update function for orbital motion
515
def update_orbits(group):
516
t = time_tracker.get_value()
517
center = center_dot.get_center()
518
519
for i, dot in enumerate(group):
520
radius = 1 + 0.3 * i
521
angle = t + i * PI / 3
522
pos = center + radius * np.array([
523
np.cos(angle), np.sin(angle), 0
524
])
525
dot.move_to(pos)
526
527
orbit_dots.add_updater(update_orbits)
528
529
# Trailing effect
530
trails = VGroup()
531
532
def add_trail_points(mob):
533
t = time_tracker.get_value()
534
if int(t * 10) % 3 == 0: # Add point every 0.3 seconds
535
for dot in orbit_dots:
536
trail_point = Dot(
537
radius=0.02,
538
color=dot.get_color(),
539
fill_opacity=0.5
540
).move_to(dot.get_center())
541
trails.add(trail_point)
542
543
trails.add_updater(add_trail_points)
544
545
self.add(center_dot, orbit_dots, trails)
546
547
# Animate the system
548
self.play(
549
time_tracker.animate.set_value(8),
550
run_time=8,
551
rate_func=linear
552
)
553
554
# Move center and watch system adapt
555
self.play(
556
center_dot.animate.shift(RIGHT * 2),
557
run_time=2
558
)
559
560
self.play(
561
time_tracker.animate.set_value(12),
562
run_time=4,
563
rate_func=linear
564
)
565
```
566
567
## Advanced Techniques
568
569
### Custom Animation Classes
570
571
```python
572
class CustomWaveAnimation(Animation):
573
def __init__(self, mobject, amplitude=1, frequency=1, **kwargs):
574
self.amplitude = amplitude
575
self.frequency = frequency
576
super().__init__(mobject, **kwargs)
577
578
def interpolate_mobject(self, alpha):
579
# Custom interpolation logic
580
wave_offset = self.amplitude * np.sin(2 * PI * self.frequency * alpha)
581
# Apply wave transformation
582
pass
583
```
584
585
### Performance Optimization
586
587
```python
588
# Efficient group animations
589
def optimize_group_animation(group, animation_func):
590
# Batch similar animations for better performance
591
return AnimationGroup(*[
592
animation_func(mob) for mob in group
593
], lag_ratio=0.02)
594
595
# Conditional animation execution
596
def conditional_animate(condition, true_anim, false_anim):
597
return true_anim if condition else false_anim
598
```
599
600
The advanced animations module in ManimGL provides sophisticated tools for creating complex, coordinated animations with intelligent object matching, continuous deformations, and advanced timing patterns essential for mathematical demonstrations and educational content.