How would i perform collision checks for 2 sprite groups?

Question:

So, i have some code over here but it doesn’t seem to work. I’m trying to make it so if my enemy falls on a tile it gets sent back to the top of the tile so it won’t phase through the floor the collisions check does work, but i don’t know how to loop through the self.enemy group and also loop through the self.tiles group to see if anyone of them collides together, the the enemy that collides gets sent back. enemy.direction.y just checks if the enemy is falling

enemytilecollision=pygame.sprite.groupcollide(self.tiles,self.enemy,False,False)
if enemytilecollision:
    for enemy in self.enemy.sprites():
        if enemy.direction.y>0:
            for tile in self.tiles.sprites():
                enemy.rect.bottom=tile.rect.top
                enemy.direction.y=0

Answers:

pygame.sprite.groupcollide returns all you need. It returns a dictionary with all tiles that collide with an enemy. And the value of each item in the dictionary is the list of enemies with which the tile collides:

enemytilecollision = pygame.sprite.groupcollide(self.tiles,self.enemy,False,False)

for tile, collidingEnemies in enemytilecollision.items():
    for enemy in collidingEnemies:
        # tile collides with enemy 
        print(tile.rect, enemy.rect)
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.