当前位置:首页 > Python > 正文

Python实现旋转地球动画 - 完整代码教程 | Python编程技巧

Python实现旋转地球动画教程

本文将教你使用Python的Pygame和Matplotlib库创建令人惊叹的3D旋转地球动画。包含完整代码实现和详细解释。

实现旋转地球的基本原理

创建3D旋转地球动画主要涉及以下技术:

  • 3D投影 - 将3D球体坐标投影到2D平面
  • 纹理映射 - 将地球贴图应用到球体表面
  • 旋转动画 - 通过改变旋转角度实现动画效果
  • 双缓冲技术 - 实现平滑的动画渲染

方法1:使用Pygame实现旋转地球

步骤1:安装所需库

pip install pygame numpy

步骤2:完整代码实现

import pygame
import numpy as np
import math
import sys

# 初始化pygame
pygame.init()

# 设置窗口尺寸
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("旋转地球 - Pygame实现")

# 地球参数
RADIUS = 150
ROTATION_SPEED = 0.005

# 创建地球表面点
def create_sphere_points(radius, num_points=100):
    points = []
    for i in range(num_points):
        for j in range(num_points):
            theta = i * 2 * math.pi / num_points
            phi = j * math.pi / num_points
            
            x = radius * math.sin(phi) * math.cos(theta)
            y = radius * math.sin(phi) * math.sin(theta)
            z = radius * math.cos(phi)
            
            points.append((x, y, z))
    return np.array(points)

# 创建地球点
sphere_points = create_sphere_points(RADIUS, 100)

# 旋转矩阵
def rotation_matrix_x(angle):
    return np.array([
        [1, 0, 0],
        [0, math.cos(angle), -math.sin(angle)],
        [0, math.sin(angle), math.cos(angle)]
    ])

def rotation_matrix_y(angle):
    return np.array([
        [math.cos(angle), 0, math.sin(angle)],
        [0, 1, 0],
        [-math.sin(angle), 0, math.cos(angle)]
    ])

# 主循环
angle = 0
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 清屏
    screen.fill((0, 0, 30))
    
    # 更新旋转角度
    angle += ROTATION_SPEED
    
    # 应用旋转矩阵
    rot_y = rotation_matrix_y(angle)
    rot_x = rotation_matrix_x(angle * 0.5)
    rotation_matrix = np.dot(rot_y, rot_x)
    
    # 投影点并绘制
    for point in sphere_points:
        rotated_point = np.dot(rotation_matrix, point)
        
        # 3D到2D投影
        z = 1 / (2 - rotated_point[2] / RADIUS)  # 透视投影因子
        x_proj = rotated_point[0] * z + WIDTH // 2
        y_proj = rotated_point[1] * z + HEIGHT // 2
        
        # 根据深度设置颜色
        depth = max(0, min(255, int(rotated_point[2] + RADIUS)))
        color = (0, 100 + depth // 2, 200 - depth // 3)
        
        # 绘制点
        if 0 <= x_proj < WIDTH and 0 <= y_proj < HEIGHT:
            pygame.draw.circle(screen, color, (int(x_proj), int(y_proj)), 1)
    
    # 添加说明文字
    font = pygame.font.SysFont(None, 24)
    text = font.render("Pygame实现旋转地球 - 按ESC退出", True, (200, 200, 255))
    screen.blit(text, (20, 20))
    
    # 更新屏幕
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()

方法2:使用Matplotlib实现旋转地球

步骤1:安装所需库

pip install matplotlib numpy

步骤2:完整代码实现

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D

# 创建图形和3D坐标轴
fig = plt.figure(figsize=(10, 8), facecolor='#0f1b2d')
ax = fig.add_subplot(111, projection='3d')

# 设置背景颜色和网格
ax.set_facecolor('#0f1b2d')
ax.grid(False)
ax.set_axis_off()

# 生成球体点
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 50)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# 创建地球表面
earth = ax.plot_surface(x, y, z, rstride=2, cstride=2, color='#3498db', 
                        edgecolor='#1e5f8a', alpha=0.8)

# 添加大陆轮廓
def add_continents(ax):
    # 简化的大陆轮廓坐标
    continents = [
        # 亚洲
        np.array([[-3, -2, 7], [-1, -4, 8], [2, -2, 8], [5, 0, 7], [3, 5, 6], [-1, 6, 5], [-3, 2, 6], [-3, -2, 7]]),
        # 北美洲
        np.array([[-8, 2, 4], [-5, 5, 5], [-2, 6, 4], [0, 5, 3], [-1, 2, 4], [-3, 0, 5], [-6, 1, 4], [-8, 2, 4]]),
        # 南美洲
        np.array([[-5, -3, 6], [-3, -6, 5], [-1, -8, 3], [0, -6, 4], [-2, -4, 6], [-5, -3, 6]]),
        # 非洲
        np.array([[1, -4, 8], [3, -1, 8], [5, 2, 7], [5, 5, 5], [3, 5, 6], [1, 2, 7], [0, -1, 8], [1, -4, 8]]),
        # 欧洲
        np.array([[-1, 6, 5], [0, 8, 3], [2, 8, 3], [3, 6, 5], [1, 5, 6], [-1, 6, 5]]),
        # 澳大利亚
        np.array([[7, -5, 4], [8, -3, 4], [9, -1, 2], [8, -3, 3], [7, -5, 4]])
    ]
    
    for continent in continents:
        ax.plot(continent[:,0], continent[:,1], continent[:,2], 
                color='#2ecc71', linewidth=1.5)

add_continents(ax)

# 设置坐标轴范围
ax.set_xlim([-12, 12])
ax.set_ylim([-12, 12])
ax.set_zlim([-12, 12])

# 旋转动画函数
def update(frame):
    ax.view_init(elev=30, azim=frame)
    return fig,

# 创建动画
ani = FuncAnimation(fig, update, frames=np.arange(0, 360, 1), 
                    interval=50, blit=False)

plt.tight_layout()
plt.show()

旋转地球效果展示

Pygame实现

使用Pygame实现的3D地球旋转动画,具有实时渲染和交互性

Matplotlib实现

使用Matplotlib实现的3D地球旋转动画,适合科学可视化和数据分析

技术总结

本文介绍了两种使用Python实现旋转地球动画的方法:

  • Pygame方法:适合创建交互式应用和游戏,性能较好,但3D功能有限
  • Matplotlib方法:适合科学可视化和数据分析,3D功能强大,但性能不如Pygame

你可以根据具体需求选择合适的方法。要提升效果,可以考虑:

  • 使用真实的地球纹理贴图代替简单着色
  • 添加云层和光照效果
  • 实现更精确的大陆轮廓
  • 添加星空背景和月球等天体

© 2023 Python编程教程 - 旋转地球实现方法

发表评论