Pygame总是感应两个矩形物体之间的碰撞

时间:2019-04-02 19:20:41

标签: python-3.x pygame sprite collision-detection

运行代码后,Pygame会立即返回Bird和Pipe发生碰撞,即使它们显然没有碰撞。

我尝试使用colliderect函数并将get_rect添加到要渲染到屏幕上的每张图片中

代码:

import pygame
from random import randint
pygame.init()

screen = pygame.display.set_mode((500, 750))
gravity = 0


class Pipe(pygame.sprite.Sprite):
    def __init__(self, x_change, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.x_change = x_change
        self.x = x
        self.y = y
        self.pic1 = pygame.image.load('file/path.png')
        self.pic1 = pygame.transform.scale(self.pic1, (28*2, 600*2)).convert_alpha()
        self.pic2 = pygame.image.load('file/path.png')
        self.pic2 = pygame.transform.scale(self.pic2, (28*2, 600*2)).convert_alpha()
        self.rect1 = self.pic1.get_rect()
        self.rect2 = self.pic2.get_rect()

    def collision(self, sprite):
        return self.rect1.colliderect(sprite) or self.rect2.colliderect(sprite)


class Bird(pygame.sprite.Sprite):
    def __init__(self, bird_width, bird_height, y_change, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.pic = pygame.image.load('file/path.png').convert_alpha()
        self.pic = pygame.transform.scale(self.pic, (bird_width, bird_height))
        self.rect = self.pic.get_rect()
        self.bird_width = bird_width
        self.bird_height = bird_height
        self.y_change = y_change
        self.x = x
        self.y = y
        self.velocity = 0
        self.term_velocity = 15


bird = Bird(40, 30, 5, 0, 0)
pipe = Pipe(3, 500, randint(30, 650))

while True:
    if pipe.collision(bird.pic.get_rect()):
        print('collision')
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    gravity += 0.01
    pygame.display.flip()
    pygame.time.Clock().tick(60)

编辑: 遵循以下Hoog的建议后,两个rect的位置均为0,0。我如何更改get_rect()的位置?

1 个答案:

答案 0 :(得分:2)

没关系,我实际上回答了我自己的问题(是)!在我说get_rect()的地方,rect的位置是(0,0)。我想通了以上的评论。我需要说:  self.rect = self.pic.get_rect(center=(self.x, self.y))现在,我可以使用它。