简体   繁体   English

python plot 上的非弹跳球

[英]Not-bouncing ball on python plot

I want to make a animated plot about a ball.我想制作一个关于球的动画 plot。 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.问题是我希望它不会在轴上反弹,而是希望它继续在 plot 中移动,但像镜子一样出现在另一侧。

 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] .一种方法是简单地将vel[bounce] = -vel[bounce]替换为pos[bounce]=-pos[bounce] This will reset the position of the balls that reach the frame to the opposite edge of the frame.这会将到达框架的球的 position 重置到框架的相对边缘。

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:这是 output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM