Python-项目实战--飞机大战-碰撞检测(8)

目标

  • 了解碰撞检测方法

  • 碰撞实现

1.了解碰撞检测方法

  • pygame提供了两个非常方便的方法可以实现碰撞检测:

pygame.sprite.groupcollide()

  • 两个精灵组所有的精灵的碰撞检测

groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict
  • 如果将dokill(布尔类型)设置为True,则发生碰撞的精灵将被自动移除

  • collided参数是用于计算碰撞的回调函数

  • 如果没有指定,则每个精灵必须有一个rect属性

代码演练

  • plane_main.pyPlaneGame类中修改__check_collide方法

def __check_collide(self):

    # 1.子弹摧毁敌机
    pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

pygame.sprite.spritecollide()

  • 判断某个精灵指定精灵组中的精灵的碰撞

spritecollide(sprite, group, dokill, collided = None) -> Sprite_list
  • 如果将dokill设置为True,则指定精灵组发生碰撞的精灵将自动移除

  • collided参数是用于计算碰撞的回调函数

  • 如果没有指定,则每个精灵必须有一个rect属性

  • 返回精灵组中跟精灵发生碰撞的精灵列表

代码演练

  • plane_main.pyPlaneGame类中修改__check_collide方法

def __check_collide(self):

    # 1.子弹摧毁敌机
    pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
    # 2.敌机撞毁英雄,此时英雄是无敌的,只有敌机会被销毁,英雄不会被销毁
    pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
  • 要想英雄也被销毁,需要用到pygame.sprite.spritecollide()返回值,是一个精灵列表,利用if判断列表的长度,如果列表里有内容,说明英雄和敌机发生了碰撞,则结束游戏

def __check_collide(self):

    # 1.子弹摧毁敌机
    pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

    # 2.敌机撞毁英雄
    enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

    # 3.判断列表是否有内容
    if len(enemies) > 0:

        # 让英雄牺牲
        self.hero.kill()

        # 结束游戏
        PlaneGame.__game_over()

2.碰撞实现

  • plane_main.pyPlaneGame类中修改__check_collide方法

def __check_collide(self):

    # 1.子弹摧毁敌机
    pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

    # 2.敌机撞毁英雄
    enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

    # 3.判断列表是否有内容
    if len(enemies) > 0:

        # 让英雄牺牲
        self.hero.kill()

        # 结束游戏
        PlaneGame.__game_over()

内容总结于:https://space.bilibili.com/37974444

代码见:https://github.com/x45w/python_feijidazhan1.git或者https://github.com/x45w/python_feijidazhan.git

猜你喜欢

转载自blog.csdn.net/aaaccc444/article/details/128983908