【问题标题】:Pygame Sprite CollisionPygame精灵碰撞
【发布时间】:2014-04-14 16:13:46
【问题描述】:

我一直致力于在 pygame 中创建一个小型的太空侵略者风格游戏。我已经快到终点了,但我想做到这一点,如果敌舰与我的船相撞,就会检测到碰撞并结束游戏。

到目前为止,我有用于检测子弹和敌舰何时发生碰撞的代码,但是当我尝试为敌人/玩家碰撞重写此代码时,它没有按预期工作,所以我认为我做错了。

有问题的代码:

for block in block_list:

    player_hit_list = pygame.sprite.spritecollide(block, player_list, True)

    for player in player_hit_list:
        explosion.play()
        block_list.remove(block)
        player_list.remove(player)
        all_sprites_list.remove(block)
        all_sprites_list.remove(player)

    if block.rect.y < +10:
        block_list.remove(block)
        all_sprites_list.remove(block)  

完整代码:http://pastebin.com/FShPuR6A

有人能告诉我为什么我的代码不起作用吗?

非常感谢

【问题讨论】:

  • 实际发生了什么?游戏永远不会退出,玩家就消失了吗?
  • @BartlomiejLewandowski 敌舰照常从玩家身边经过,没有任何东西消失,游戏也没有退出:(

标签: python-3.x pygame collision detection


【解决方案1】:
class Block(pygame.sprite.Sprite):
    def __init__(self, color):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("spaceship.png")
        self.rect = self.image.get_rect()

    def update(self):
        self.rect.y += 1

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.x=0
        self.y=0
        self.image = pygame.image.load("alien.png")
        self.rect = self.image.get_rect()

    def update(self):
        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]

乍一看,你有一个 Block 类,其中有一张像外星人一样移动的宇宙飞船的图片。 Player 类,具有外星人图像,并随鼠标移动。

我的建议是重命名这些类,以便您知道什么是什么。更容易发现错误。

编辑:

看起来你的播放器根本不动:

def render(self):
        if (self.currentImage==0):
            screen.blit(self.image, (self.x, self.y))

您通过self.rect.x 更新播放器,但您使用self.xself.y 绘制。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多