Knight Knight - 1 month ago 8
Python Question

How to get BOTH COLLIDE sprite objects in pygame

How to get both collide object in pygame

As i say

allSprite = pygame.sprite.Group()
Bullets = pygame.sprite.Group()
Enemies = pygame.sprite.Group()

bullet = Bullet()
enemy = Enemy()
Bullets.add(bullet)
Enemies.add(enemy)

hits = pygame.sprite.collide(Enimies,Bullets)
for hit in hits:
hit.damage()


It only get Enemy object but i want both objects cause i need bullet damage too.if there is another way?

And thank you.

Answer Source

You can use the groupcollide function for this: http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.groupcollide

You will get back a dictionary of Enemies (keys) and for each Enemy, a list of the Bullets that hit it (values). Then you can do something like this:

hits = pygame.sprite.groupcollide(Enemies, Bullets, False, True)
for enemy in hits:
    for bullet in hits[enemy]:
        enemy.damage(bullet.damage)