如何解决 pygame 中这些圆圈的碰撞?

How to fix these circles' collision in pygame?

所以,基本上我希望两个圆圈以加速度 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()

你实际做的是绘制圆圈,然后更新那里的位置,最后更新显示。
改变顺序。更新圆圈的位置,然后在当前位置绘制它们,最后更新显示。所以圆圈显示在实际位置。

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()

另外,1个循环绝对够了。只需在主应用程序循环中验证 if r:

如果您不希望圆圈在最终位置相交,则必须更正位置:

if x2-x1 <= 50: 
    r = False
    d = x2-x1
    x1 -= (50-d) // 2
    x2 += (50-d) // 2