如何修复pygame中这些圆圈的碰撞?

问题描述 投票:0回答:1

所以,基本上我希望两个圆以加速度 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()
python pygame collision-detection
1个回答
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()

此外,1个循环绝对足够了。只需在主应用程序循环中验证

if r:
即可。

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

if x2-x1 <= 50: 
    r = False
    d = x2-x1
    x1 -= (50-d) // 2
    x2 += (50-d) // 2 
© www.soinside.com 2019 - 2024. All rights reserved.