2015-09-26 22 views
1

我想要以初始角度初始速度發射的投射物的路徑動畫。我嘗試修改這裏找到代碼:http://matplotlib.org/examples/animation/simple_anim.html動畫python中的投射物的路徑

我的代碼如下所示:

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() 

的代碼,如圖所示,給我繪圖窗口,但沒有軌跡和沒有動畫。我在這裏搜索了一下,看看這個問題是否已經在其他地方問過了,我還沒有找到它。如果有問題,請鏈接到已經回答的問題。任何幫助是極大的讚賞。謝謝大家。

+0

你的代碼是不行的 - 在'animate()'和'init()'中沒有關閉圓括號。我還得到一個'AttributeError:'FigureCanvasMac'對象沒有屬性'copy_from_bbox''和'AttributeError:'FigureCanvasMac'對象沒有屬性'restore_region'' –

回答

3

我能得到以下使用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的基礎知識;這將支付鉅額的股息。

+1

謝謝。我可以從這裏爲我的目的調整它。我運行2.7,但它仍然按預期工作。謝謝您的幫助! – Gary