Search code examples
pythonpygamesprite

Pygame: how to return relative positions of sprites colliding


I've got two groups:

a pygame.sprite.GroupSingle() for the player (or I have the player sprite object itself not in any group)

a pygame.sprite.Group() for all the objects in the level.

What's the simplest/best way to check for collision between the player and the sprite group and return the relative position of those two sprites (or anything that will tell me you can't go a certain direction so to not enter the object). This is simply for creating platforms


Solution

  • The sprites already have their position inside the sprite.rect. So it's reasonably easy to first determine the list of colliding objects, and then loop through the results working out the relative position distances.

    collided_with = pygame.sprite.spritecollide( player, platform_group, False )
    for platform in collided_with:
        relative_x = player.rect.x - platform.rect.x
        relative_y = player.rect.y - platform.rect.y
    

    Note in the above player is a sprite, not a group.