Get the pixels which are colliding with the Surface

138 Views Asked by At

Right now, I have a collision detection in pygame which checks if two rctangles overlap or not...what I am trying to do is check the transparency of a the surface and if the alpha value is less then 10, stop player from walking into it..

Currently, Im doing this:

for i in range(0,self.rect.w):
    for j  in range(0,self.rect.h):
        if player.rect.collidepoint((i,j)) and self.image.get_at((i,j))[3]<10:
            #STOP PLAYER

But it is a real pain on the Processor. Is there another way to get the collision pixel coordinates in pygame??

1

There are 1 best solutions below

0
On

Use pygame.mask.Mask objects and overlap() or overlap_mask().

overlap() :

Returns the first point of intersection encountered between this mask and othermask.
[...]
Returns point of intersection or None if no intersection.

overlap_mask():

Returns a Mask, the same size as this mask, containing the overlapping set bits between this mask and othermask.

A mask can be created form a pyame.Surface with pygame.mask.from_surface()-

e.g.:

player_mask = pygame.mask.from_surface(player.image)
self.mask = pygame.mask.from_surface(self.image)
offset = (player.rect.x - self.rect.x), (player.rect.y - self.rect.y)
first_intersection_point = self.mask.overlap(player_mask , offset)
if first_intersection_point:
    print("hit")