Cereal
Cereal

Reputation: 13

Is there a way in pygame to find collisions within a group

The pygame module utilizes groups in a variety of its collision detection methods.

I have been trying to find a way to find collisions for a sprite against other members that are contained in the same group.

In the example -

pygame.sprite.spritecollide(creature, creaturegroup, False)

this continues to provide a false positive for collision detection, which I believe is due to the 'creature' sprite being contained within the 'creaturegroup' group. Any suggested workarounds for finding collisions within a group?

Upvotes: 1

Views: 692

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

One way is to create a temporary Group that contains all of the Sprites but the one you want to test:

test_group = pagame.sprite.Group([s for s in creaturegroup if s != creature])
pygame.sprite.spritecollide(creature, test_group, False) 

Another option is to write your own test function, that skips equal objects:
(See pygame.sprite.collide_rect())

def collide_if_not_self(left, right):
    if left != right:
        return pygame.sprite.collide_rect(left, right)
    return False
pygame.sprite.spritecollide(creature, creaturegroup, False, collide_if_not_self)

Upvotes: 3

Related Questions