pygame中的collide.rect是如何工作的

2 投票
1 回答
2993 浏览
提问于 2025-04-17 17:30

我在理解colliderect和精灵(sprites)是怎么一起工作的方面遇到了一些麻烦。我对这个概念有个大概念,但每次我试着把它用到我的游戏里,就会出现错误信息“attributeError: 'pygame.surface' object has no attribute 'rect'”。

ufo_lvl_1 = pygame.image.load("ufo1.png") 
bullet = pygame.image.load("bullet.png")

class Bullet(pygame.sprite.Sprite):

    def __init__(self):
    # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self) 

        self.image = bullet
        self.damage = 5
        self.rect = self.image.get_rect()

    def update(self):
        if 1 == 1:
            self.rect.x += 15
        if self.rect.x >1360:
            self.kill()

class ufo1(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)

        self.image = ufo_lvl_1
        self.health = 10
        self.rect = self.image.get_rect()
    def update(self):
        if 1==1:
            self.rect.x  -= 10
            if self.rect.colliderect(bullet.rect):
                self.health -= bullet.damage
                if self.health >= 0:
                    self.kill()
                bullet.kill()            

基本上,我的所有精灵都能正常工作(除了ufo1),但一旦我创建了ufo1这个精灵,程序就崩溃了,我不知道该怎么解决。

提前谢谢大家。

1 个回答

0

你把你的类叫做 Bullet,然后把这个类的表面也叫做 bullet。当你调用 colliderect 的时候,它在检查 bullet,而不是 Bullet 或者你给 Bullet 类的对象起的其他名字。

撰写回答