Question

Is there a way in pygame to detect if a rect is fully inside a mask?

I know that there is rect in rect collision and collidepoint (point in rect collision) but is there any way to detect if a rect is inside a mask?

Thanks

Was it helpful?

Solution

I don't believe there is any function supplied by pygame to do that. It would definitely be somewhat challenging, because of the "shapeless" possibilities of a mask. One possibility which might work for you would be to first get a list of the bounding rects of the mask (a list of rects which together "contain" all of the points of the mask) and check if your rect is inside any of these rects:

bounding_rects = mask.get_bounding_rects()
for b_rect in bounding_rects:
    if b_rect.contains(test_rect):
        print "Rect is inside mask"

Of course with this solution, if the rect is inside the mask, but not inside any one particular bounding rect, the test will fail. Here's an idea of how you might handle that, with the tradeoff of a little bit of lost precision:

bounding_rects = mask.get_bounding_rects()
mask_rect = bounding_rects[0].unionall(bounding_rects)
if mask_rect.contains(test_rect):
    print "Rect is inside mask"

This solution unions all of the bounding rects of the mask into one rect, which has the possibility of covering area that none of the bounding rects covered (if two rects have a gap of 10 pixels between each other and are unioned together, the new rect will contain that gap)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top