【问题标题】:'Ground' object has no attribute 'rect'\'Ground\' 对象没有属性 \'rect\'
【发布时间】:2022-08-21 15:41:49
【问题描述】:

我是 pygame 和一般编码的新手,我收到一条让我感到困惑的错误消息。

我想检测我的玩家精灵和 Ground() 类中的任何精灵之间的碰撞。我尝试使用 spritecollideany,但收到错误消息 \'Ground\' object has no attribute \'rect.\'

我的玩家等级

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.x = x
        self.y = y
        self.image = pygame.image.load(\"marioLeft.png\")
        self.rect = self.image.get_rect(midtop = (self.x, self.y))

    def Move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT]:
            self.x += 5
        if keys[pygame.K_LEFT]:
            self.x -= 5

    def Draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

我的地面课

class Ground(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.x = x
        self.y = y
        self.width = width
        self.height = height

        self.ground_surf = pygame.Surface((self.width, self.height))
        self.ground_rect = self.ground_surf.get_rect(midtop = (self.x, self.y))
        self.ground_surf.fill(\'White\')

    def DrawGround():
        for entity in ground_sprites:
            screen.blit(entity.ground_surf, entity.ground_rect)

给我一条错误消息的代码。

if pygame.sprite.spritecollideany(player, ground_sprites):
        pass

    标签: python pygame


    【解决方案1】:

    pygame.sprite.spritecollideany 使用pygame.sprite.Sprite 对象的rect 属性来检测碰撞。所以每个对象都需要有一个rect 属性:

    class Ground(pygame.sprite.Sprite):
        def __init__(self, x, y, width, height):
            super().__init__()
            self.x = x
            self.y = y
            self.width = width
            self.height = height
    
            self.image = pygame.Surface((self.width, self.height))
            self.rect = self.image .get_rect(midtop = (self.x, self.y))
            self.image .fill('White')
    
        def DrawGround():
            for entity in ground_sprites:
                screen.blit(entity.ground_surf, entity.ground_rect)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多