Skip to main content

SmallerRectForSpriteCollision — wiki

To get sprite collsion methods to use a different member Rect can be useful. I use my Sprite.rect for rendering purposes, and want a smaller rect for collision detection. To get that effect I added the method below to my Charactor class:

# TODO: make this method more generic, so it can be used outside of your
# program.
def am_in_collision(self):
    v_shrink_by=.7
    h_shrink_by=.45
    smaller_me=self.rect.inflate(-self.rect.width*h_shrink_by,
        -self.rect.height*v_shrink_by)
    allsprites2=allsprites.copy()
    allsprites2.remove(self)
    smaller_all=[sprite.rect.inflate(-sprite.rect.width*h_shrink_by,
        -sprite.rect.height*v_shrink_by) for sprite in allsprites2]
    return bool(smaller_me.collidelistall(smaller_all))