【问题标题】:Animating the path of a projectile in python在python中动画弹丸的路径
【发布时间】:2015-09-26 14:23:22
【问题描述】:

我正在尝试为以初始角度以初始速度发射的弹丸的路径设置动画。我试图修改这里找到的代码:http://matplotlib.org/examples/animation/simple_anim.html

我的代码如下所示:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

g = 9.8                               #value of gravity
v = 20                                #initial velocity
theta = 20*np.pi/180                  #initial angle of launch in radians
tt = 2*v*np.sin(theta)/g              #total time of flight
t = np.linspace(0, tt, 0.01)          #time of flight into an array
x = v*np.cos(theta)*t                 #x position as function of time
line, = ax.plot(x, v*np.sin(theta)*t-(0.5)*g*t**2) #plot of x and y in time

def animate(i):
    line.set_xdata(v*np.cos(theta)*(t+i/10.0))
    line.set_ydata(v*np.sin(theta)*(t+i/10.0)-(0.5)*g*(t+i/10.0)**2)  
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_xdata(np.ma.array(t, mask=True))
    line.set_ydata(np.ma.array(t, mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200),
init_func=init, interval=25, blit=True)
plt.show()

代码,如图所示,给了我绘图窗口,但没有轨迹和动画。我在这里搜索过,看看其他地方是否有人问过这个问题,但我还没有找到。如果已被询问,只需链接到已回答的问题。任何帮助是极大的赞赏。谢谢大家。

【问题讨论】:

  • 您的代码无法正常工作 - animate()init() 中缺少右括号。我还收到了AttributeError: 'FigureCanvasMac' object has no attribute 'copy_from_bbox'AttributeError: 'FigureCanvasMac' object has no attribute 'restore_region'

标签: python animation matplotlib projectile


【解决方案1】:

我能够使用 python 3.4.3 获得以下功能:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

g = 9.8                                                        #value of gravity
v = 10.0                                                       #initial velocity
theta = 40.0 * np.pi / 180.0                                   #initial angle of launch in radians
t = 2 * v * np.sin(theta) / g                                  
t = np.arange(0, 0.1, 0.01)                                    #time of flight into an array
x = np.arange(0, 0.1, 0.01)
line, = ax.plot(x, v * np.sin(theta) * x - (0.5) * g * x**2)   # plot of x and y in time

def animate(i):
    """change the divisor of i to get a faster (but less precise) animation """
    line.set_xdata(v * np.cos(theta) * (t + i /100.0))
    line.set_ydata(v * np.sin(theta) * (x + i /100.0) - (0.5) * g * (x + i / 100.0)**2)  
    return line,

plt.axis([0.0, 10.0, 0.0, 5.0])
ax.set_autoscale_on(False)

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200))
plt.show()

轴需要重新缩放,以及许多其他事情发生了变化。

它并不完美,但显示了一个沿着所需轨迹的弹丸。

您现在可以使用它并查看代码并摆弄它来学习。我还建议你花一点时间来学习 numpy/pyplot 的基础知识;这将在未来带来丰厚的回报。

【讨论】:

  • 谢谢。为了我的目的,我可以从这里调整它。我正在运行 2.7,但它仍然按预期工作。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多