2

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

Kingsley
  • 14,398
  • 5
  • 31
  • 53

2 Answers2

3

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.

Kingsley
  • 14,398
  • 5
  • 31
  • 53
2

As far as I know Group and GroupSingle do not provide any functions for checking for collision. Sprites in pygame also provide a function collide_rect, that uses the bounds of the sprites to detect a collision. The downside is, that in many cases the bounds of the sprites are not the intended collision bounds.

A common approach in game dev is to use extra collision objects associated with the player, enemy or obstacle. In pygame there is a class Rect that can do that for you with the function colliderect. See: https://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect

In many cases rectangles are enough. For more complex collisions you have to define polygons. There is another stackoverflow question covering this: Basic 2d collision detection

Christian
  • 739
  • 1
  • 5
  • 15