Skip to main content
 首页 » 编程设计

python之collide.rect 如何在 pygame 中工作

2025年05月04日8insus

我在理解 colliderect 如何与 Sprite 一起工作时遇到了一些问题。我对此有一个很好的想法,但每当我尝试将其实现到我的游戏中时,我只会收到错误消息“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()             

基本上我所有的 Sprite 都可以工作(不包括 ufo1),但是当我创建一个 ufo1 Sprite 时它崩溃了,我不知道如何修复它。

提前致谢。

请您参考如下方法:

您将您的类称为 Bullet,并将您的表面称为该类 Bullet。当您调用 colliderect 时,您将检查 bullet 而不是 Bullet 或您命名为类 Bullet 的对象的任何内容