酷代码 AI
菜单
服务商

Python 实现 3D 可转动蓝色立体爱心与粒子玫瑰互变动画:代码揭秘及开发避坑指南

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation # 创建图形和3D坐标轴 fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') ax.set_facecolor('black') fig.patch.set_facecolor('black') ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) # 心形参数方程 def heart(t): x = 16 * (np.sin(t)3) y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t) z = np.zeros_like(t) return x, y, z # 玫瑰花参数方程(简化版螺旋玫瑰) def rose(t): n = 3 # 螺旋圈数 r = t / (2 * np.pi) x = r * np.cos(n * t) y = r * np.sin(n * t) z = 5 * t return x, y, z # 生成粒子 num_particles = 1000 t_heart = np.linspace(0, 2 * np.pi, num_particles) t_rose = np.linspace(0.1, 2 * np.pi, num_particles) # 避免除以零 xh, yh, zh = heart(t_heart) xr, yr, zr = rose(t_rose) # 归一化到相似尺寸 scale_heart = 0.3 xh *= scale_heart yh *= scale_heart zh *= scale_heart # 统一归一化范围 max_val = max(xr.max(), yr.max(), zr.max(), xh.max(), yh.max(), zh.max()) xr /= max_val / 1.5 yr /= max_val / 1.5 zr /= max_val / 1.5 # 初始化粒子位置(从爱心开始) points, = ax.plot(xh, yh, zh, 'o', markersize=1.2, color='cyan', alpha=0.9) # 动画状态 state = {'morph': 0, 'direction': 1} # morph: 0=heart, 1=rose; direction: 1正向,-1反向 def animate(frame): morph_progress = (frame % 200) / 100.0 # 0到2循环 if morph_progress > 1: morph_progress = 2 - morph_progress # 往返变化 state['direction'] = -1 else: state['direction'] = 1 # 插值混合 alpha = morph_progress x = (1 - alpha) * xh + alpha * xr y = (1 - alpha) * yh + alpha * yr z = (1 - alpha) * zh + alpha * zr # 旋转效果 theta = frame * 0.02 x_rot = x * np.cos(theta) - y * np.sin(theta) y_rot = x * np.sin(theta) + y * np.cos(theta) z_rot = z + 0.1 * frame % 20 - 10 # 轻微上下浮动 points.set_data(x_rot, y_rot) points.set_3d_properties(z_rot) # 动态颜色调整(根据形态) color_val = (0.7, 1.0, 1.0, 0.8 + 0.2 * np.sin(frame * 0.1)) # 淡蓝到亮蓝 points.set_color(color_val) ax.view_init(elev=20, azim=frame * 0.5) # 摄像机缓慢旋转 return points, ani = animation.FuncAnimation(fig, animate, frames=400, interval=50, blit=False) plt.tight_layout() plt.show() 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 1. Matplotlib 3D动画在某些环境下渲染效率较低,大量粒子可能导致卡顿,建议控制粒子数量或使用更高效的可视化库如`vispy`。 2. 参数方程生成的形状尺寸差异较大,必须进行归一化处理,否则插值变形会显得突兀或溢出视野。 3. 动画循环中频繁更新视图角度和数据时,需注意内存泄漏风险,尤其是在长时间运行的场景中。 ######[AI写代码神器 | 1021点数解答 | 2025-11-05 13:58:30]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]