I am creating various class with objects moving randomly in the screen. What I am doing:
object = obj(screen)
object2 = Object2(screen)
object3 = Object(screen)
then I add the object and the object 2 in a group like:
group2 = pygame.sprite.Group(object, object2)
and the object3 in a different group like:
group = pygame.sprite.Group(object3)
Then I am checking the group2 with the group if there is collide, but with this method I don't know which object collide the other object:
if pygame.sprite.spritecollide(group, group2, False, pygame.sprite.collide_mask):
To handle the collision of sprites in two different groups, you can use pygame.sprite.groupcollide()
:
pygame.sprite.groupcollide()
Find all sprites that collide between two groups.
groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict
This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect attribute of each Sprite or by using the collided function if it is not None.
Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.
If either dokill argument is True, the colliding Sprites will be removed from their respective Group.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a “rect” value, which is a rectangle of the sprite area, which will be used to calculate the collision.
So, given group
and group2
, you can use it like:
result = pygame.sprite.groupcollide(group, group, False, False)
and the result is a dict
containing the infotmation you're looking for, as the documentation states.