Search code examples
pythonpython-2.7pygamecollision-detection

Pygame circle collision?


I am using pygame to make a simple game. I am having issues with circle collisions. I am getting the following error:

"AttributeError: 'pygame.Rect' object has no attribute 'rect'"

Here is the particular code I am having issues with below:

if pygame.sprite.collide_circle(hero_circle, enemy_circle):
    gameover()

Solution

  • Use pygame.mask to create a collision mesh for your objects and use the mesh to do collision detections.

    In more detail:

    1. Create an image file for both of your circles and set the bg color to something you will not use anywhere else.
    2. Set that color to "transparent" in your image editor.
    3. Import the images.
    4. Create a mesh for them with pygame.mask and set it to make transparent pixels non-collidable.
    5. Use the generated mask as your collision detection mesh.
    6. PROFIT

    (Technically this is just doing collision detection of a circle shaped area on a rectangle, but who cares!)