程序检测碰撞,即使精灵并未实际碰撞'pygame.sprite.collide_rect

1 投票
2 回答
1163 浏览
提问于 2025-04-17 10:01

我的目标是让我的程序能够检测到小球精灵(ball sprite)与任何一个“g_ball”精灵发生碰撞。当我运行代码时,它似乎能够检测到碰撞,我还加了一个“print”语句来测试它……但是它一直在不停地打印“progress”,即使这些精灵并没有碰在一起。以下是代码:

while 1:
    screen.blit(background, (0,0))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()


        if event.type == KEYDOWN:
            if event.key == K_a:
                m_x = -4
                s+=1
            elif event.key == K_d:
                m_x = +4
                s2+=1
        if event.type == KEYUP:
            if event.key == K_a:
                m_x = 0
            elif event.key == K_d:
                m_x = 0

    x+= m_x
    y+= m_y      

    ball = pygame.sprite.Sprite()
    ball.image = pygame.image.load('red_ball.png').convert()
    ball.rect = ball.image.get_rect()
    ball.image.set_colorkey((white))
    screen.blit(ball.image,(x,y))
    if x > 640:
        x = 0
    if x < 0:
        x = 640


    g_ball = pygame.sprite.Sprite()
    g_ball.image = pygame.image.load('green_ball.png').convert()
    g_ball.rect = g_ball.image.get_rect()
    g_ball.image.set_colorkey(white)
    screen.blit(g_ball.image,(50,t))
    t+=5
    if t > 521:
        t = 0
    collision = pygame.sprite.collide_rect(ball, g_ball)
    if collision == True:
        print ('PROGRESS!!!')

2 个回答

0

nightcracker说得对。你知道你在这个循环里做了什么吗?这个循环本来应该尽可能快地运行。你在每次循环中都创建了两个新的球,加载了图片,还把它们放在(0,0)的位置,然后手动把它们显示在屏幕上的某个位置。最后这部分的意思是你把它们显示在某个地方,但不是它们真正的位置(你确实用ball.rect=ball.image.get_rect()设置了它们的真实位置)。它们实际上是在(0,0)的位置,并且一直在碰撞。

你把它们显示到屏幕上的方式不太好,你应该使用一个渲染器。总之,你可能应该先看看一些教程,了解什么是Surface,什么是Sprite。要注意你在主循环里放了什么(为什么你总是创建新的球?它们可以在启动时创建一次),这样你的代码会更整洁,帧率也会提高。

0

这是因为你没有为碰撞设置偏移量,你只是把偏移量传给了 screen.blit

你修正后的代码应该是这样的:

...
ball.rect = ball.image.get_rect()
ball.rect.topleft = (x, y)
...
g_ball.rect = g_ball.image.get_rect()
g_ball.rect.topleft = (50, t)
...

撰写回答