Is there a way to make sure a sprite collides with 2 sprites in a group?

Viewed 31

So, i'm trying to make it so when my player collides with a tile in the group self.tiles, and if my player is running at the tile in the right direction, set the player back to the left of that tile. Problem is, i can't use

for tile in self.tiles.sprites():
            if tile.rect.colliderect(player.rect):

as, since i also have a vertical collision where it uses the same thing to detect whether a player is standing on it. Only difference between vertical and horizontal, is that the player would collide with two tiles at once in horizontal, so i'd like to see if there's a way to detect if a player touches 2 of the tile sprites in self.tiles.sprites (if there's a more efficient method i'd like to hear it as well)

1 Answers

See pygame.sprite.spritecollide():

Return a list containing all Sprites in a Group that intersect with another Sprite.

So if you want to know all the tiles the player collides with, you have to use pygame.sprite.spritecollide():

listOfCollindingTiles = pygame.sprite.spritecollide(player, tile, False)
for tile in listOfCollindingTiles:
    print(tile.rect)

Another way to handle horizontal and vertical movements and collisions is to perform the horizontal and vertical movements separately:

  • horizontal movement
  • collisions detection and restriction of the X-coordinate of the player
  • vertical movement
  • collisions detection and restriction of the Y-coordinate of the player
Related