Search code examples
pythonpygamecollision-detectioncollisionpygame-surface

Why is my Pygame Collision always colliding?


I have been trying to use Pygame collision, but nothing I have tried has works. Now I have ended up with this:

player_collison_box = player.get_rect()   
hole_collision_box = hole.get_rect() 
if player_collison_box.colliderect(hole_collision_box):
    print('collision')

It doesn't throw out any errors or anything, but it just always prints 'collide'. I don't know if the collide boxes are too big or both at the same spot or something, but can you help me?


Solution

  • pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, but it returns a rectangle that always starts at (0, 0) since a Surface object has no position.
    The Surface is placed at a position when it is blit to the display.

    You've to set the location of the rectangle, by a keyword argument. In the following (player_x, player_y) are the coordinates of the player and (hole_x, hole_y) ar eth coordinates of the hole:

    player_collison_box = player.get_rect(topleft = (player_x, player_y))
    hole_collision_box = hole.get_rect(topleft = (hole_x, hole_y))
    if player_collison_box.colliderect(hole_collision_box):
        print('collision')