更新动画变量 [英] Updating animation variable
问题描述
我正在尝试编写一个程序来模拟2个物体的轨道。我已经能够创建两个物体的轨道的动画,并试图在动画的顶角添加一个计数器以显示系统的动能。
I am trying to write a program to simulate the orbit of 2 bodies. I have been able to create an animation of the orbits of the 2 bodies and am trying to add a counter at the top corner of the animation to display the kinetic energy of the system.
我将动能存储在一个名为 ke的列表中,希望动画显示列表中与物体位置相对应的值。
I have the kinetic energies stored in a list called "ke" and want the animation to display the values in the list corresponding to the positions of the bodies.
但是,当我尝试编写显示动能所需的代码时,我必须返回变量 energy_text ,但是我得到了错误: AttributeError:'list'对象没有属性'set_animated'。
However, when I try to write the code needed to display the kinetic energies I have to return the variable "energy_text", but I get an error : AttributeError: 'list' object has no attribute 'set_animated'.
如何使变量正确返回/更新?
fig = plt.figure()
ax = plt.axes()
ax = plt.axes(xlim=(-12*10**6, 12*10**6), ylim=(-12*10**6, 12*10**6))
patches = []
patches.append(plt.Circle((r_phobos_h[0][0],r_phobos_h[0][1]),5*10**5,color="b", animated=True))
patches.append(plt.Circle((r_mars_h[0][0],r_mars_h[0][1]),5*10**6,color="orange", animated=True))
energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)
def init():
for i in range(0, len(patches)):
ax.add_patch(patches[i])
energy_text.set_text('')
return patches, energy_text
def animate(i):
patches[0].center = (r_phobos_h[i][0], r_phobos_h[i][1])
patches[1].center = (r_mars_h[i][0], r_mars_h[i][1])
energy_text.set_text(ke[i])
return patches, energy_text
numframes = len(t)
anim = FuncAnimation(fig, animate, init_func=init, frames = numframes, interval=0.01,blit=True)
plt.show()
推荐答案
通过编写返回补丁,energy_text
,您不会将平面列表返回给动画
。
通过将行更改为返回补丁+ [energy_text]
,它应该可以工作:
By writing return patches, energy_text
you are not returning a flat list back to the animation
.
By changing the lines to return patches + [energy_text]
it should work:
return patches, energy_text # -> [[patch_a, patch_b, ...patch_n], text1]
return patches + [energy_text] # -> [patch_a, patch_b, ...patch_n, text1]
这篇关于更新动画变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!