这段代码使用Manim库创建了一个3D球极坐标可视化演示动画。可视化球坐标系中的几何图形,特别展示了如何将球极坐标(r, θ, φ)转换为三维笛卡尔坐标,并在球体表面上绘制曲线。具体来说,它实现了以下功能:

1. 场景设置

  • 创建三维场景,设置初始相机视角
  • 建立三维坐标系(X, Y, Z轴)

2. 主要视觉元素

  • 透明球体:作为参考框架,半径=3
  • 参考网格:球体表面的经纬网格
  • 两条示例曲线:
    • 红色螺旋路径:φ随θ变化,形成螺旋效果
    • 绿色赤道圆:固定在φ=π/2(赤道平面)

3.代码分享

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
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 SphericalDemo(ThreeDScene):
def construct(self):
self.set_camera_orientation(phi=65 * DEGREES, theta=-40 * DEGREES)
self.add_fixed_in_frame_mobjects(head("球极坐标可视化", "Sphere / (r, theta, phi)"))
R = 1.8
axes = ThreeDAxes(x_length=5, y_length=5, z_length=5,
axis_config={"color": GREY_B})
sphere = Sphere(radius=R, resolution=(24, 24)).set_fill(BLUE, opacity=0.10)
sphere.set_stroke(BLUE_E, width=1, opacity=0.5)
grid = VGroup()
for i in range(1, 6):
z = R * np.cos(i * PI / 6)
rr = R * np.sin(i * PI / 6)
lat = Circle(radius=rr, color=BLUE_E).set_stroke(width=1.5, opacity=0.45)
lat.shift(z * OUT)
grid.add(lat)
for k in range(6):
mer = Circle(radius=R, color=BLUE_E).set_stroke(width=1.5, opacity=0.35)
mer.rotate(PI / 2, axis=RIGHT).rotate(k * PI / 6, axis=OUT)
grid.add(mer)
def spiral(t):
phi = 0.25 + (t / (4 * PI)) * (PI - 0.5)
rad = R * 1.02
return np.array([rad * np.sin(phi) * np.cos(t),
rad * np.sin(phi) * np.sin(t),
rad * np.cos(phi)])
curve = ParametricFunction(spiral, t_range=[0, 4 * PI, 0.02], color=RED).set_stroke(width=6)
self.add(axes, sphere, grid)
self.play(Create(curve), run_time=3.4)
self.begin_ambient_camera_rotation(rate=0.15)
self.wait(2.0)
self.stop_ambient_camera_rotation()
self.add_fixed_in_frame_mobjects(foot("红色螺旋:theta 绕轴旋转,phi 由北极走向南极"))
self.wait(1.2)

来看渲染的视频效果:

下载 Python 脚本

渲染的视频文件比较大,十六M左右,所以加载的时间也长一些,网站的服务器资源也有限,大家可以本地跑一下代码,不过因为电脑配置的因素,渲染的市场也会不同,希望能够帮助到大家。