Анимация пути снаряда в питоне

Я пытаюсь оживить траекторию снаряда, запущенного с начальной скоростью под начальным углом. Я попытался изменить код, найденный здесь: 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()

Код, как показано, дает мне окно сюжета, но не траекторию и не анимацию. Я искал здесь, чтобы узнать, спрашивали ли об этом где-то еще, и я еще не нашел. Если это было задано, просто дайте ссылку на уже отвеченный вопрос. Любая помощь приветствуется. Спасибо всем.


person Gary    schedule 26.09.2015    source источник
comment
Ваш код как есть не работает - в animate() и init() отсутствуют закрывающие скобки. Я также получаю AttributeError: 'FigureCanvasMac' object has no attribute 'copy_from_bbox' и AttributeError: 'FigureCanvasMac' object has no attribute 'restore_region'   -  person Reblochon Masque    schedule 26.09.2015


Ответы (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; это принесет огромные дивиденды в будущем.

person Reblochon Masque    schedule 26.09.2015
comment
Спасибо. Я могу настроить его отсюда для своих целей. Я использую 2.7, но он все еще работает, как и ожидалось. Спасибо за помощь! - person Gary; 26.09.2015