请用python做出一个3D的太阳系直观观看天体运动
要创建一个3D的太阳系模型,可以使用Python中的matplotlib库来实现。下面是一个简单的示例代码,展示了如何使用matplotlib创建一个太阳、地球和月球的模型,并观察它们的运动。
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 创建画布
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 定义太阳、地球和月球的初始位置
sun_pos = np.array([0, 0, 0])
earth_pos = np.array([10, 0, 0])
moon_pos = np.array([10, 0, 1])
# 绘制太阳
ax.scatter(sun_pos[0], sun_pos[1], sun_pos[2], color='yellow', s=100)
# 绘制地球和月球
earth = ax.scatter(earth_pos[0], earth_pos[1], earth_pos[2], color='blue', s=20)
moon = ax.scatter(moon_pos[0], moon_pos[1], moon_pos[2], color='gray', s=10)
# 设置坐标轴范围
ax.set_xlim([-15, 15])
ax.set_ylim([-15, 15])
ax.set_zlim([-15, 15])
# 动画更新函数
def update(i):
# 计算地球和月球的新位置
angle = np.radians(i * 3)
earth_pos[0] = 10 * np.cos(angle)
earth_pos[1] = 10 * np.sin(angle)
moon_pos[0] = earth_pos[0] + 1 * np.cos(angle * 10)
moon_pos[1] = earth_pos[1] + 1 * np.sin(angle * 10)
# 更新地球和月球的位置
earth._offsets3d = (earth_pos[0], earth_pos[1], earth_pos[2])
moon._offsets3d = (moon_pos[0], moon_pos[1], moon_pos[2])
# 创建动画
ani = plt.FuncAnimation(fig, update, frames=np.arange(0, 120, 2), interval=50)
# 显示动画
plt.show()
运行以上代码,将会创建一个显示太阳、地球和月球运动的动画。地球绕太阳旋转,同时月球绕地球旋转。你可以根据需要调整代码中的各种参数,如位置、颜色和速度等,以满足你的需求
原文地址: https://www.cveoy.top/t/topic/hE24 著作权归作者所有。请勿转载和采集!