问题
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