Search code examples
pythonalgorithmpygame2d2d-games

How can I stop enemies from overlapping pygame


I'm trying to find a way to have enemies track the player in my 2d game (pygame) but not clump up

Currently, when I shoot at them, the bullet collides into and damages all of the enemies that are clumped. I would like it to be a hoard but spread out just enough to where I can't hit every single enemy at once

It looks like this

Here's a gif of them clumping

I'm not sure how I would get the individual values of the enemies' positions so I can move them when they collide or how I should move them

This is what I currently have for the enemies to track the player:

     for aliveEnemies in enemy:
        if playerObj.rect.x - aliveEnemies.rect.x != 0:
            if playerObj.rect.x > aliveEnemies.rect.x:
                aliveEnemies.rect.x += 1
            if playerObj.rect.x < aliveEnemies.rect.x:
                aliveEnemies.rect.x -= 1
        if playerObj.rect.y - aliveEnemies.rect.y != 0:
            if playerObj.rect.y > aliveEnemies.rect.y:
                aliveEnemies.rect.y += 1
            if playerObj.rect.y < aliveEnemies.rect.y:
                aliveEnemies.rect.y -= 1"

Any help or points in the right direction would be greatly appreciated


Solution

  • You can do collision detection between the enemies, to determine which ones are too close. You'll also need to change their behavior, to decide what to do when they actually get too close.

    If you know you'll never get too many enemies, you can try comparing every enemy with every other enemy. This will take O(N^2) work, but that is probably OK if N is limited.

    If you are comparing every enemy to every other anyway, you have a wider variety of options than just "collision detection": like the Boids algorithm (which does collision avoidance instead).