Search code examples
pythonpygamespritecollision-detectioncollision

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


I have been trying to create an enemy moving system for my top down pygame 2d game. But my two enemies always end up by getting over one another. This is why I decided to create a method that will stop the enemies from overlaping one and other but I don't know how to check for a collision between an enemy in the group and the rest of the group because when I do so the enemy is always thinking he has collided with another enemy but he just collided with himself. Is there an easy way to fix this? See the comment in the code below for more explanation

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')

Solution

  • One option for you is 2 nested loops::

    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')
    

    The outer loop iterates through all enemies. The inner loop iterates from the i+1th enemy to the end. This means that the collision between every 2 enemies is only tested once.