SpriteCollide Only Running Once Per Collision

隐身守侯 提交于 2020-12-14 06:39:42

问题


I'm checking missileGroup to see if any instances of missile collided with any instances enemy in enemyGroup. When run, it prints "Hit" for the first loop, but it ignores the second for loop. Why is that?

 #### Imagine this is in a game loop ####
        for missile in missileGroup:
            if pygame.sprite.spritecollide(missile, enemyGroup, False) :
                print("Hit")

        
        for enemy in enemyGroup:
            if pygame.sprite.spritecollide(enemy, missileGroup, False) == True:
                print("HI")

回答1:


pygame.sprite.spritecollide() doesn't return True or False, but it return a list containing all Sprites in a Group that intersect with another Sprite. You have to evaluate whether the list is not empty instead of comparing the result with True:

if pygame.sprite.spritecollide(enemy, missileGroup, False) == True:

if pygame.sprite.spritecollide(enemy, missileGroup, False):

Anyway use pygame.sprite.groupcollide() to find all sprites that collide between two groups.

if pygame.sprite.groupcollide(missileGroup, enemyGroup, False, False):
    print("Hit")

See pygame.sprite.spritecollide():

Return a list containing all Sprites in a Group that intersect with another Sprite.

See pygame.sprite.groupcollide()

This will find collisions between all the Sprites in two groups.

Therefore the arguments to spritecollide() must be a pygame.sprite.Sprite object and a pygame.sprite.Group object. the arguments to groupcollide() must be two pygame.sprite.Group objects.
A list of pygame.sprite.Sprite objects instead of the Group does not work.

missileGroup = pygame.sprite.Group()
enemyGroup = pygame.sprite.Group()

Furthermore read about kill()

The Sprite is removed from all the Groups that contain it.

Hence if you call kill() in the 1st loop, the 2nd loop won't work, because the sprite is removed from all Groups.

You call kill() in the reset methods. missile.reset() respectively eachEnemy.reset() causes the 2nd loop to fail.



来源:https://stackoverflow.com/questions/65053443/spritecollide-only-running-once-per-collision

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