I want to make a animated plot about a ball. Something like the one bellow here. The problem is that i want it to not bounce in the axis, instead i want that it keeps moving in the plot but appearing on the other side like it was a mirror.
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1)
plt.clf()
plt.axis([-10,10,-10,10])
n=10
pos=(20*np.random.sample(n*2)-10).reshape(n,2)
vel=(0.3*np.random.normal(size=n*2)).reshape(n,2)
sizes=100*np.random.sample(n)+100
colors=np.random.sample([n,4])
circles=plt.scatter(pos[:,0], pos[:,1], marker='o', s=sizes, c=colors)
for i in range(100):
pos=pos+vel
bounce=abs(pos)>10
vel[bounce] = -vel[bounce]
circles.set_offsets(pos)
plt.draw()
plt.pause(0.05)
plt.show()
One way to do this is to simply replace the line vel[bounce] = -vel[bounce]
with pos[bounce]=-pos[bounce]
. This will reset the position of the balls that reach the frame to the opposite edge of the frame.
Full code below:
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure(1)
plt.axis([-10,10,-10,10])
n=10
pos=(20*np.random.sample(n*2)-10).reshape(n,2)
vel=(0.3*np.random.normal(size=n*2)).reshape(n,2)
sizes=100*np.random.sample(n)+100
colors=np.random.sample([n,4])
circles=plt.scatter(pos[:,0], pos[:,1], marker='o', s=sizes, c=colors)
for i in range(100):
pos=pos+vel
bounce=abs(pos)>10
pos[bounce]=-pos[bounce]
circles.set_offsets(pos)
plt.draw()
plt.pause(0.05)
plt.show()
And this is the output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.