【问题标题】:How to fix these circles' collision in pygame? [duplicate]如何在pygame中修复这些圆圈的碰撞? [复制]
【发布时间】:2019-12-13 13:22:30
【问题描述】:

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

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

    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 
    

    【讨论】:

    • 很有见地。没想到。
    猜你喜欢
    • 2013-09-12
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多