Pygame - sprite collision with sprite group

元气小坏坏 提交于 2019-12-01 11:13:40

This is your problem:

for enemy in all_sprites:
    gets_hit = pygame.sprite.spritecollideany(umb, all_sprites)
    if gets_hit:
        all_sprites.remove(enemy)

You're looping through the group, and if any sprite collides, deleting all of them.

You don't need to loop through the group - the collision functions take care of that. You just need to use the spritecollide function, which compares a sprite versus a group. That function will return a list of collisions, as well as using the DOKILL flag to delete them automatically:

        gets_hit = pygame.sprite.spritecollide(umb, all_sprites, True)

spritecollideany checks if the sprite collides with any sprite in the group and returns this sprite, so gets_hit is a trueish value as long as the collided sprite in the group is not removed and the if gets_hit: block gets executed. That means the code in the for loop simply keeps deleting every sprite in the group that appears before the collided sprite is reached and removed. A simple fix would be to check if the hit sprite is the enemy: if enemy == gets_hit:, but the code would still be inefficient, because spritecollideany has to loop over the all_sprites group again and again inside of the for loop.

I recommend to use spritecollide instead of spritecollideany as well, since it's more efficient and just one line of code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!