因此,基本上,我希望两个圆以加速度1彼此加速。我想在圆碰撞时停止。 但是,代码在冲突之前就停止了。这是因为它计算出它们在下一次迭代中会一直通过。这样就停止了。如何对此进行改进,以便提供所需的结果。 我已要求它打印圆的位置和速度,以便您可以在运行时查看数据。 预先感谢。
import pygame
pygame.init()
w=1000
h=500
dis=pygame.display.set_mode((w,h))
pygame.display.set_caption("test2")
t=10
x1=50
x2=w-50
y1=250
y2=y1
v=0
r=True
def circles():
pygame.draw.circle(dis,(0,200,0),(x1,y1),25)
pygame.draw.circle(dis,(0,0,200),(x2,y2),25)
run=True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
while r:
pygame.time.delay(t)
dis.fill((255,255,255))
circles()
print(x2,x1,(x2-x1),v,t)
x1+=v
x2-=v
v+=1
if x2-x1<=50: # THIS LINE STOPS THE CIRCLES
r=False
pygame.display.update()
pygame.quit()
答案 0 :(得分:2)
您实际要做的是绘制圆,然后在此处更新位置,最后更新显示。
更改顺序。更新圆的位置,然后在当前位置绘制它们,最后更新显示。这样圆圈就会显示在实际位置上。
run=True
while run:
for event in pygame.event.get():
if event.type==pygame.QUIT:
run=False
pygame.time.delay(t)
if r:
x1 += v
x2 -= v
v += 1
if x2-x1 <= 50:
r=False
print(x2,x1,(x2-x1),v,t)
dis.fill((255,255,255))
circles()
pygame.display.update()
此外,一个循环绝对足够。只需在主应用程序循环中验证if r:
。
如果您不希望圆在最终位置相交,则必须更正位置:
if x2-x1 <= 50:
r = False
d = x2-x1
x1 -= (50-d) // 2
x2 += (50-d) // 2