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

标签 python pygame collision-detection

我在理解 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 的对象的任何内容

关于python - collide.rect 如何在 pygame 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15146679/

相关文章:

python - Flask - 在应用程序上下文之外工作

python - pygame与子弹的碰撞找不到碰撞

python - Python pygame.mixer不会无限播放音乐

python - 如何设置不等式来检查 "consumption"(基本上是冲突)

python - 用python模拟处理?

javascript - 如何在 JavaScript 中找到两条线段的交点?

C#/XNA - 二维碰撞引擎故障?

python - sklearn 的 DecisionTreeClassifier 中的 "splitter"属性有什么作用?

python - Python无效语法为何?c

Python:选择位数来表示二进制数