pygame中pygame.sprite.groupcollide的知识

在照例程做pygame外星人小游戏时遇到精灵组碰撞检测的问题,不是很明白。以下是pygame.sprite.groupcollide()的官方文档

Find all sprites that collide between two groups.
groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict

This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect attribute of each Sprite or by using the collided function if it is not None.

Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.

If either dokill argument is True, the colliding Sprites will be removed from their respective Group.

The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.

说的我有点云里雾里,运行游戏程序打印一下pygame.sprite.groupcollide()的输出(为方便测试这里采用了大子弹)

1 {}
2 {<Bullet sprite(in 0 groups)>: [<Alien sprite(in 0 groups)>]}
3 {<Bullet sprite(in 0 groups)>: [<Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>]}

可以看出pygame.sprite.groupcollide()的返回值会有这三种。精灵组无碰撞发生则返回空字典({}的布尔值是Flase),发生碰撞则返回字典,其中子弹为键,外星人为值。每当检测到碰撞发生都会返回一个这样的字典。这样以下增加得分的代码也就很好理解了。

1 collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
2     if collisions:
3         stats.score += ai_settings.alien_points

 

posted @ 2019-04-04 10:33  椰汁软糖  阅读(10539)  评论(1编辑  收藏  举报