在动画制作中,轨迹特效常常用于增强视觉效果,而带有闪光效果的轨迹更是能够吸引观众的注意力。

本文将介绍如何使用Manim动画库实现闪光轨迹特效。

1. 实现原理

下面的GlowingTracedPath类参考了Manim中的TracePath类,增加了闪光和渐变色的效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from manim import *
class GlowingTracedPath(VMobject):
def __init__(
self,
traced_point_func: Callable,
stroke_width: float = 2,
stroke_color: ParsableManimColor | None = WHITE,
dissipating_time: float | None = None,
gradient_colors: list[ParsableManimColor] | None = None, #
glow_speed: int = 2,
**kwargs,
):
"""
构造函数

Parameters:
traced_point_func - 回调函数,用于获取被追踪点的当前位置
stroke_width - 轨迹的宽度,默认为 2
stroke_color - 轨迹的基本颜色,默认为白色
dissipating_time - 轨迹的消散时间
gradient_colors - 颜色渐变列表
glow_speed - 闪光速度,控制轨迹闪光效果的快慢
**kwargs - 用于传递额外的关键字参数到父类VMobject的构造函数中
"""
super().__init__(
stroke_color=stroke_color,
stroke_width=stroke_width,
**kwargs,
)
self.glow_speed = glow_speed

if not gradient_colors is None:
self.set_color_by_gradient(gradient_colors)

self.set_stroke(opacity=0.2)

self.traced_point_func = traced_point_func
self.dissipating_time = dissipating_time
self.time = 1

self.add_updater(self.update_path)

def update_path(self, mob, dt):
# 更新轨迹中的点
new_point = self.traced_point_func()
if not self.has_points():
self.start_new_path(new_point)

self.time += dt
t = self.time * self.glow_speed # 控制脉冲速度
intensity = 0.25 * np.sin(t) + 0.75 # 0.5-1之间波动
# 动态调整透明度
self.set_stroke(
opacity=intensity, # 透明度波动
)

self.add_line_to(new_point)
# 轨迹消散
if self.dissipating_time:
if self.time - 1 > self.dissipating_time:
nppcc = self.n_points_per_curve
self.set_points(self.points[nppcc:])

初始化函数(__init__)的参数,代码中已经有详细的注释,不再赘述。

至于更新轨迹的update_path方法,它的关键逻辑有:

  • 获取新点:通过traced_point_func获取被追踪点的当前位置,并将其添加到轨迹的末尾
  • 动态调整透明度:使用正弦函数np.sin生成一个在0.5到1之间波动的强度值intensity,并通过set_stroke方法动态调整轨迹的透明度,从而实现闪烁效果
  • 轨迹消散:如果设置了dissipating_time参数,当轨迹的持续时间超过该值时,会移除轨迹的起始部分,使轨迹逐渐消失

此外,GlowingTracedPath类还会通过set_color_by_gradient方法为轨迹设置颜色渐变效果。

2. 使用示例

接下来我们通过几个示例来看看如何使用这个特效。

2.1. 渐变色轨迹

基于上面我们实现的GlowingTracedPath类,实现一个渐变色的轨迹非常简单。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from manim import *
import numpy as np
def head(cn, en):
t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
return VGroup(t, s)
def foot(cn):
return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
class GlowingTracedPath(VMobject):
"""闪光轨迹:收集被追踪点的历史位置,按时间切换渐变色。"""
def __init__(self, traced_point_func, stroke_width=7,
gradient_colors=None, dissipating_time=None,
glow_speed=2, **kwargs):
super().__init__(**kwargs)
self.traced_point_func = traced_point_func
self.gradient_colors = gradient_colors or [BLUE, RED, YELLOW]
self.dissipating_time = dissipating_time
self.glow_speed = glow_speed
self.stroke_width = stroke_width
self.points_list = []
self.elapsed = 0.0
self.set_stroke(self.gradient_colors[0], width=stroke_width)
self.add_updater(self.update_path)
def update_path(self, mob, dt):
mob.elapsed += dt
mob.points_list.append(np.array(mob.traced_point_func(), dtype=float))
if mob.dissipating_time:
keep = max(2, int(mob.dissipating_time * 60))
mob.points_list = mob.points_list[-keep:]
if len(mob.points_list) >= 2:
mob.set_points_as_corners(mob.points_list)
idx = int(mob.elapsed * mob.glow_speed) % len(mob.gradient_colors)
mob.set_stroke(mob.gradient_colors[idx], width=mob.stroke_width)
class GlowBasic(Scene):
def construct(self):
self.add(head("闪光轨迹:自定义 VMobject", "GlowingTracedPath / add_updater"))
a = Dot(RIGHT * 2.6, color=YELLOW, radius=0.13)
halo = Circle(radius=0.30, color=YELLOW).set_stroke(width=3, opacity=0.5)
halo.add_updater(lambda m: m.move_to(a.get_center()))
b = GlowingTracedPath(a.get_center, gradient_colors=[BLUE, RED, YELLOW])
self.add(a, halo, b)
self.play(a.animate(path_arc=PI / 2).shift(LEFT * 2.6), run_time=2.6)
self.play(a.animate(path_arc=-PI / 2).shift(LEFT * 2.6), run_time=2.6)
b.clear_updaters()
self.play(FadeIn(foot("updater 每帧追加新点,颜色按时间循环切换")), run_time=0.4)
self.wait(1.2)

代码中,轨迹b追踪点a的位置,形成一个由参数gradient_colors指定的渐变色轨迹。

下载 Python 脚本

2.2. 轨迹逐渐消失

上面的示例中,轨迹不会消失,通过参数dissipating_time,可以指定轨迹存在的时间(单位:秒)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from manim import *
import numpy as np
def head(cn, en):
t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
return VGroup(t, s)
def foot(cn):
return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
class GlowingTracedPath(VMobject):
"""闪光轨迹:收集被追踪点的历史位置,按时间切换渐变色。"""
def __init__(self, traced_point_func, stroke_width=7,
gradient_colors=None, dissipating_time=None,
glow_speed=2, **kwargs):
super().__init__(**kwargs)
self.traced_point_func = traced_point_func
self.gradient_colors = gradient_colors or [BLUE, RED, YELLOW]
self.dissipating_time = dissipating_time
self.glow_speed = glow_speed
self.stroke_width = stroke_width
self.points_list = []
self.elapsed = 0.0
self.set_stroke(self.gradient_colors[0], width=stroke_width)
self.add_updater(self.update_path)
def update_path(self, mob, dt):
mob.elapsed += dt
mob.points_list.append(np.array(mob.traced_point_func(), dtype=float))
if mob.dissipating_time:
keep = max(2, int(mob.dissipating_time * 60))
mob.points_list = mob.points_list[-keep:]
if len(mob.points_list) >= 2:
mob.set_points_as_corners(mob.points_list)
idx = int(mob.elapsed * mob.glow_speed) % len(mob.gradient_colors)
mob.set_stroke(mob.gradient_colors[idx], width=mob.stroke_width)
class GlowDissipate(Scene):
def construct(self):
self.add(head("轨迹消散:只保留最近若干帧", "dissipating_time"))
a = Dot(RIGHT * 2.6 + UP * 1.0, color=WHITE, radius=0.13)
b = GlowingTracedPath(a.get_center,
gradient_colors=[BLUE, RED, YELLOW],
dissipating_time=0.7)
self.add(a, b)
self.play(a.animate(path_arc=PI).shift(LEFT * 5.2), run_time=3.0)
self.play(a.animate(path_arc=-PI).shift(RIGHT * 5.2), run_time=3.0)
b.clear_updaters()
self.play(FadeIn(foot("限制历史点数量,尾迹就不会无限拉长")), run_time=0.4)
self.wait(1.0)

将轨迹b的dissipating_time设置为0.5,也就是新产生的轨迹会在0.5秒后逐渐消失。

下载 Python 脚本

2.3. 轨迹闪烁

最后,来看看轨迹的闪光效果,下面的通过设置两种不同的glow_speed(闪烁的速度),

来比较不同速度下的闪烁效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from manim import *
import numpy as np
def head(cn, en):
t = Text(cn, font="STLiti", font_size=27).to_edge(UP)
s = Text(en, font="Consolas", font_size=20, color=YELLOW).next_to(t, DOWN, buff=0.10)
return VGroup(t, s)
def foot(cn):
return Text(cn, font="STLiti", font_size=20, color=YELLOW).to_edge(DOWN)
class GlowingTracedPath(VMobject):
"""闪光轨迹:收集被追踪点的历史位置,按时间切换渐变色。"""
def __init__(self, traced_point_func, stroke_width=7,
gradient_colors=None, dissipating_time=None,
glow_speed=2, **kwargs):
super().__init__(**kwargs)
self.traced_point_func = traced_point_func
self.gradient_colors = gradient_colors or [BLUE, RED, YELLOW]
self.dissipating_time = dissipating_time
self.glow_speed = glow_speed
self.stroke_width = stroke_width
self.points_list = []
self.elapsed = 0.0
self.set_stroke(self.gradient_colors[0], width=stroke_width)
self.add_updater(self.update_path)
def update_path(self, mob, dt):
mob.elapsed += dt
mob.points_list.append(np.array(mob.traced_point_func(), dtype=float))
if mob.dissipating_time:
keep = max(2, int(mob.dissipating_time * 60))
mob.points_list = mob.points_list[-keep:]
if len(mob.points_list) >= 2:
mob.set_points_as_corners(mob.points_list)
idx = int(mob.elapsed * mob.glow_speed) % len(mob.gradient_colors)
mob.set_stroke(mob.gradient_colors[idx], width=mob.stroke_width)
class GlowSpeedCompare(Scene):
def construct(self):
self.add(head("闪光频率对比", "glow_speed = 8 / 16"))
a1 = Dot(LEFT * 3 + UP * 1.2, color=WHITE, radius=0.12)
a2 = Dot(LEFT * 3 + DOWN * 1.2, color=WHITE, radius=0.12)
b1 = GlowingTracedPath(a1.get_center, gradient_colors=[BLUE, RED, YELLOW], glow_speed=8)
b2 = GlowingTracedPath(a2.get_center, gradient_colors=[BLUE, RED, YELLOW], glow_speed=16)
lab1 = Text("glow_speed = 8", font="Consolas", font_size=20, color=GREY_A).to_edge(LEFT).shift(UP * 1.7)
lab2 = Text("glow_speed = 16", font="Consolas", font_size=20, color=GREY_A).to_edge(LEFT).shift(DOWN * 1.7)
self.add(lab1, lab2, a1, a2, b1, b2)
self.play(a1.animate.shift(RIGHT * 5.6), a2.animate.shift(RIGHT * 5.6), run_time=3.2)
self.play(a1.animate.shift(LEFT * 5.6), a2.animate.shift(LEFT * 5.6), run_time=2.2)
b1.clear_updaters(); b2.clear_updaters()
self.play(FadeIn(foot("glow_speed 越大,同一段轨迹里颜色切换越频繁")), run_time=0.4)
self.wait(1.0)

下载 Python 脚本

左边的心形glow_speed=8,右边的心形glow_speed=16,所以右边的闪烁速度会快一些。

3. 总结

通过GlowingTracedPath类,我们可以轻松地在Manim中实现带有闪光效果的轨迹。

这个类通过动态调整透明度和颜色渐变,结合轨迹的实时更新,创造出了引人注目的视觉效果。

无论是用于数学动画还是其他创意项目,这种特效都能为你的作品增添独特的魅力。