pygame中的collide.rect如何工作 [英] how does collide.rect work in pygame

查看:451
本文介绍了pygame中的collide.rect如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解碰撞如何与精灵一起工作时遇到了一些麻烦。我对此有个好主意,但是每当我尝试将其实现到游戏中时,我都会收到错误消息 attributeError:'pygame.surface'对象没有属性'rect'。

I'm having some trouble understanding how colliderect works with sprites. I have a good idea about it, but whenever I try to implement it into my game, I just get the error message "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时,它崩溃了,我不知道如何解决

Basically all my sprites work (excluding ufo1), but the moment I create a ufo1 sprite it crashes and I don't know how to fix it.

预先感谢。

推荐答案

您称自己的课程为项目符号和您的班级项目符号表面。当您调用colliderect时,您要检查bullet而不是Bullet或您命名为Bullet类的对象

you called your class Bullet and your surface for that class bullet. When you are calling colliderect you are having it check bullet instead of Bullet or whatever you named the object of class Bullet

这篇关于pygame中的collide.rect如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆