问题描述
我正在检查 missileGroup
,以查看导弹
的任何实例是否与 enemyGroup
中的任何实例 enemy
发生冲突.在运行时,它会打印"Hit".对于第一个循环,但它忽略了第二个for循环.为什么会这样?
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")
推荐答案
pygame.sprite.spritecollide()
不返回 True
或 False
,但返回包含所有内容的列表组中的 Sprites 与另一个 Sprite 相交.您必须评估列表是否不为空,而不是将结果与 True
进行比较:
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):
无论如何都使用 pygame.sprite.groupcollide()
来查找在两组之间碰撞的所有精灵.
Anyway use pygame.sprite.groupcollide()
to find all sprites that collide between two groups.
if pygame.sprite.groupcollide(missileGroup, enemyGroup, False, False):
print("Hit")
请参见 pygame.sprite.spritecollide()
:
请参见 pygame.sprite.groupcollide()
因此, spritecollide()
的参数必须是 pygame.sprite.Sprite
对象和 pygame.sprite.Group
对象. groupcollide()
的参数必须是两个 pygame.sprite.Group
对象. pygame.sprite.Sprite
对象而不是 Group 的列表不起作用.
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()
进一步了解 kill()
Furthermore read about kill()
因此,如果您在第一个循环中调用 kill()
,则第二个循环将不起作用,因为该精灵已从所有组中删除.
Hence if you call kill()
in the 1st loop, the 2nd loop won't work, because the sprite is removed from all Groups.
您可以在 reset
方法中调用 kill()
. missile.reset()
分别 eachEnemy.reset()
导致第二个循环失败.
You call kill()
in the reset
methods. missile.reset()
respectively eachEnemy.reset()
causes the 2nd loop to fail.
这篇关于SpriteCollide每次碰撞仅运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!