I’m new to using masks in Pygame and I’m having trouble with them.
I have already learned how to check collisions between two masks but I’m wondering about an effective way to check collisions between a rect and a mask.
I’ve seen this post on stackoverflow : collisions between rect and mask but I didn’t understand the answer and I don’t even want to create my own function to do this work as I think there is a way to do it with the pygame functions.
So I tried to find a way myself and this is my attempt:
class Rectangle: def __init__(self): self.x, self.y = 240, 300 self.rect = Rect(self.x, self.y, 50, 50) # I have made a function to get the coordinates of the center of an image or a rect self.center = center(self.x, self.y, self.rect) self.mask = pygame.mask.Mask((50, 50), True) # some code def blit(self): # update the pos of the center self.center = center(self.x, self.y, self.rect) pygame.draw.rect(MyScreen, 'green', self.rect, border_radius=2) # some code class Circle: def __init(self): self.image = load('redcircle.png') self.x, self.y = 400, 220 self.mask = pygame.mask.from_surface(self.image) self.center = center(self.x, self.y, self.image) def blit(self): # update the pos of the center self.center = center(self.x, self.y, self.image) MyScreen.blit(self.image, (self.x, self.y)) myrectangle = Rectangle() mycircle = Circle() collision_detection(): # I also created a function called 'offset' to calculate the offset # However I still don't understand what an offset is, that's why I'm just calculating it automatically if mycircle.mask.overlap(myrectangle.mask.get_rect(center=myrectangle.center), offset(mycircle, myrectangle)): print('it worked !')
This code didn’t work And I got a “TypeError: argument 1 must be pygame.mask.Mask, not pygame.Rect” error.
So now I’m looking for a simple way to detect collisions between a mask and a rect object and as I mentionned in the comments in the code above, I still don’t understand what is an offset that the function
pygame.mask.overlap takes though I also checked this post.
So I’m looking for an easy explanation, thanks !