如何验证同一 pygame.sprite.Group() 中两个精灵之间的碰撞?

How to verify collision between two sprites in the same pygame.sprite.Group()?

我一直在尝试为我的自上而下 pygame 2d 游戏创建一个敌人移动系统。但我的两个敌人总是以克服彼此而告终。这就是为什么我决定创建一种方法来阻止敌人相互重叠,但我不知道如何检查组中敌人与组中其他人之间的碰撞,因为当我这样做时,敌人总以为自己撞上了另一个敌人,结果撞上了自己。有没有简单的方法来解决这个问题? 请参阅下面代码中的注释以获取更多解释

enemies = self.enemies.sprites()
for enemy in enemies:
    if pygame.sprite.spritecollide(enemy,self.enemies,False,pygame.sprite.collide_mask): # This is the part I would like to change because the enemy is always saying it is colliding with himself but I want him to see if he is in collision with the other enemies not himself even though he is part of that group
        print('collision')

您的一个选择是 2 个嵌套循环::

enemies = self.enemies.sprites()
for i, enemy1 in enumerate(enemies):
    for enemy2 in enemies[i+1:]:
        if pygame.sprite.collide_mask(enemy1, enemy2):
            print('collision')

外层循环遍历所有敌人。内层循环从第i+1个敌人开始迭代到最后。这意味着每2个敌人之间的碰撞只测试一次。