如何使用Manim在球体表面创建多条轨迹路径?
Manim实现球面多点绕z轴旋转并保留轨迹的问题解决
问题根源
你直接复制代码修改参数后,点在球内走小圆周的核心原因是:原代码用path_along_circles绕原点旋转,但只有赤道上的点(z坐标为0)绕原点旋转才会贴合球面;对于其他球面点,正确的旋转逻辑应该是绕z轴旋转,此时点到z轴的距离保持不变,z坐标也不变,自然能维持在球面上。而Transform配合path_along_circles的方式并不适配3D空间中绕轴旋转的场景,改用Rotate动画更直接可靠。
修正后的代码
以下是实现多个球面点绕z轴旋转并保留轨迹的完整代码:
from manim import * import numpy as np class SpherePointsRotate(ThreeDScene): # 单位球面参数方程 def func(self, u, v): return np.array([np.sin(u) * np.cos(v), np.sin(u) * np.sin(v), np.cos(u)]) def construct(self): # 坐标轴 axes = ThreeDAxes( x_range=[-2,2], x_length=4, y_range=[-2,2], y_length=4, z_range=[-2,2], z_length=4, axis_config={"include_ticks":False, "include_tip":False} ) z_line = Line3D(start=np.array([0,0,3]), end=np.array([0,0,-3]), color=YELLOW_A, thickness=0.005) # 单位球面 surface = Surface( lambda u, v: axes.c2p(*self.func(u, v)), u_range=[0, np.pi], v_range=[0, 2*np.pi], resolution=30, fill_opacity=0.75, fill_color=GRAY, stroke_opacity=0 ) # 设置相机角度 self.move_camera(phi=70 * DEGREES, theta=45 * DEGREES) # 定义多个球面点(可自行添加更多) point1 = Dot3D(point=axes.coords_to_point(1,0,0), color=RED) point2 = Dot3D(point=axes.coords_to_point(np.sin(np.pi/4), 0, np.cos(np.pi/4)), color=BLUE) point3 = Dot3D(point=axes.coords_to_point(0, np.sin(3*np.pi/4), np.cos(3*np.pi/4)), color=GREEN) # 批量创建轨迹追踪器 traces = [ TracedPath(point.get_center, stroke_color=point.color) for point in [point1, point2, point3] ] for trace in traces: self.add(trace) # 场景初始化 self.play(FadeIn(axes), Write(surface), run_time=0.5) self.wait() self.play(Indicate(z_line)) self.play(FadeOut(axes)) self.wait(2) # 显示所有点 self.play(FadeIn(point1), FadeIn(point2), FadeIn(point3)) self.wait(0.5) # 所有点绕z轴旋转2π self.play( Rotate(point1, angle=2*PI, axis=Z_AXIS, run_time=3), Rotate(point2, angle=2*PI, axis=Z_AXIS, run_time=3), Rotate(point3, angle=2*PI, axis=Z_AXIS, run_time=3), rate_func=linear ) self.wait(2) self.move_camera(phi=0 * DEGREES, theta=45 * DEGREES, run_time=2) self.wait(2)
关键修改说明
- 替换动画逻辑:用
Rotate动画替代原有的Transform+path_along_circles,Rotate支持指定axis参数(这里用Z_AXIS),会自动计算符合3D空间规则的旋转轨迹,保证点始终在球面上。 - 批量处理元素:用列表推导式批量创建点和对应的轨迹追踪器,减少重复代码,方便扩展更多点。
- 贴合球面的旋转逻辑:绕z轴旋转时,点的z坐标保持不变,到z轴的距离(
sqrt(x²+y²))也不变,因此始终满足球面方程x²+y²+z²=1。
内容的提问来源于stack exchange,提问作者spooleey
相关产品推荐
相关产品推荐

