I'm making a platformer in Pygame. One of the sprites I'm using is a flag, and I want to detect if the player collides with the flagpole (just like in Super Mario Bros). The problem is that the image is wider than the flagpole, because of the flag itself. I build the Rect for every sprite based on their image, just like so:

def initialize_rect(self, pos, correction = 0):
    self.rect = self.image.get_rect(topleft = pos)

Doing this, a collision is detected when the player touches the leftmost part of the image, which is a long way from the pole, so it looks terribly wrong.

I'm trying to figure out a way to change the collision box of the sprite, but nothing I try seems to work properly. I've tried the Rect.inflate() method, but that yielded no success. It shrinks the Rect from right to left, and if I then try to change the location of the Rect, the image changes its position too.

I could just make another sprite to detect collisions and somehow link it to the flag, but that would force me to change my design.

Is there a way to change the collision boxes of sprites directly in Pygame?

  • \$\begingroup\$ I found a solution for this, but as a newbie I can't answer my own question within the first 8 hours. I'll post it as soon as I can. Feel free to answer if you think you have a good solution yourself. \$\endgroup\$
    – cangrejo
    Dec 30, 2012 at 13:01

1 Answer 1


I came up with a solution myself for this that did not have too big an impact in my design. When checking for collisions, instead of using the Rect associated with the sprite I use a new method called get_hit_box(), which calculates and returns a new Rect. So instead of

if player.rect.colliderect(flag.rect): 

I have

if player.rect.colliderect(flag.get_hit_box()): 

The method get_hit_box() returns a Rect which has the same center as the Rect of the image but different dimensions. This allows me to define the collision Rect I want, regardless of what the image is. To prevent having to change too much code, the get_hit_box() method in the parent class of all sprites just returns the unchanged Rect of the image, self.image.get_rect(). Every sprite now has that method, and I redefine it only in those sprites where special collision behavior is needed.

Hope this helps someone else.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .