I recently added collision detection to Eccoes using PyGame. It wasn’t as straightforward as I hoped that it would be.
Collision detection in PyGame is based around sprite groups. The methods sprite.spritecollide() and sprite.spritecollideany() checks to see if a specific sprite is colliding with sprites inside the group. The examples that I looked at used sprite groups to represent the other objects in the game and not the player object. This made collision detection easy and straightforward.
In my game I currently maintain two sprite groups. One is called visibleObjects and the other is called gameObjects. I didn’t think it would be a good idea to have another sprite group with all of the objects that aren’t the main character because I also want to track collisions between enemy characters and the terrain. Instead I looked for a more general solution. VisibleObjects contain all the objects that I want to do collision detection between.
My collision detection code is that following:
def getCollision(self, obj):
result = pygame.sprite.spritecollideany(
In the code I removed the current object from the visibleObject group, use spritecollide, and then replace the object in the visibleObject group. I do this because the object that I’m testing is a part of the visibleObject list. This should be reasonably fast and it will keep me from having to keep track of lots of sprite groups.