如何修复Pygame报错:AttributeError: 'Bullet'对象无'rect'属性
解决Pygame子弹生成时的AttributeError问题
报错原因很明确:Pygame的sprite.Group.draw()方法会自动读取每个精灵的rect属性来确定图像绘制位置,但你的Bullet类里只定义了hitbox,没有rect,所以触发了AttributeError: 'Bullet' object has no attribute 'rect'。
有两种解决方式:
方式一:直接使用rect属性(推荐)
Pygame的Sprite类设计就是围绕rect属性展开的,不管是绘制还是碰撞检测都能直接用它,没必要额外定义hitbox。修改代码如下:
class Bullet(pygame.sprite.Sprite): def __init__(self ,x, y, direction): pygame.sprite.Sprite.__init__(self) self.speed = 10 self.image = bullet_img self.rect = self.image.get_rect() self.rect.center = (x,y) self.direction = direction def update(self): self.rect.x += self.direction * self.speed if self.rect.right < 0 or self.rect.left > SCREEN_WIDTH: self.kill()
方式二:保留hitbox并同步rect
如果确实需要单独的hitbox用于碰撞检测(比如碰撞盒和图像尺寸不一致),那必须新增rect属性并和hitbox保持位置同步:
class Bullet(pygame.sprite.Sprite): def __init__(self ,x, y, direction): pygame.sprite.Sprite.__init__(self) self.speed = 10 self.image = bullet_img self.hitbox = self.image.get_rect() self.hitbox.center = (x,y) # 复制hitbox的位置给rect self.rect = self.hitbox.copy() self.direction = direction def update(self): self.hitbox.x += self.direction * self.speed # 同步rect的位置 self.rect.x = self.hitbox.x if self.hitbox.right < 0 or self.hitbox.left > SCREEN_WIDTH: self.kill()
内容的提问来源于stack exchange,提问作者bobby_52
相关产品推荐
相关产品推荐

