Search code examples
pythonpygamespritecollision-detection

Pygame detect collision between circle and square


For my pygame project, I want to detect collision between 2 square sprites. However, one of the sprite is supposed to behave as a square, the other as a circle

pygame.sprite.collide_rect() is supposed to check collision between 2 square, interpreted as square http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect

pygame.sprite.collide_circle() is supposed to check collision between 2 square, but interpreted as circle http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle

So in short, I want a mix with pygame.sprite.collide_rect() and pygame.sprite.collide_circle(). Is it possible ?


Solution

  • I am not sure how to mix the two, but I did make a collision detection that came the closest i could to what you want, here it is:

    if circle_x < rect_x + circle_width and circle_x + rect_width > rect_x and circle_y < rect_y + circle_height and rect_height + circle_y > rect_y:
        #put whatever code you need here
    

    This puts the circle into an imaginary box that is just large enough to go around the circle, then when the imaginary box collides with the rectangle the code you need to activate activates.