1

I am trying to test the collision between a platform and the player. These platforms are images with a rhumbas, so regular rectangle collision won't work very well. The code down below starts printing true when the player is at the top left of the screen, but not where the platform actually is. I don't see what I am doing wrong so any help is appreciated.

for i in range(len(self.platforms)):
    # Masks
    feet_mask = pygame.mask.from_surface(self.feet.convert_alpha())
    platform_mask = pygame.mask.from_surface(self.platforms[i][4].convert_alpha())
    # Images
    feet_rect = self.feet.get_rect()
    platform_rect = self.platforms[i][4].get_rect()
    feet_rect.topleft = (self.feet_rect[0], self.feet_rect[1])
    platform_rect.topleft = (self.platforms[i][0], self.platforms[i][1])
    offset_x, offset_y = (platform_rect.left - feet_rect.left), (platform_rect.top - feet_rect.top)

    if platform_mask.overlap(feet_mask, (offset_x, offset_y)) != None:
        print('true')
        break
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    Related [Pygame mask collision](https://stackoverflow.com/questions/60077813/pygame-mask-collision/60078039#60078039) and [Pygame collision with masks is not working](https://stackoverflow.com/questions/57455811/pygame-collision-with-masks-is-not-working/57499484#57499484) – Rabbid76 Nov 07 '20 at 19:48

1 Answers1

1

the coumputation of the offset is wrong. The offset parameter of the method overlap() is the relative position of the othermask in relation to the pygame.mask.Mask object.
So the offset is calculated by subtracting the coordinates of feet_rect from the coordinates of platform_rect:

offset_x, offset_y = (platform_rect.left - feet_rect.left), (platform_rect.top - feet_rect.top)

offset_x, offset_y = (feet_rect.left, platform_rect.left), (feet_rect.top, platform_rect.top)
if platform_mask.overlap(feet_mask, (offset_x, offset_y)) != None:
    print('true')
    break
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Thank you for the answer, but when I do this it still prints true at position where the sprites are not colliding, but instead of the top left it is the bottom right. Is this a problem somewhere else in my code not related to the collision? –  Nov 07 '20 at 20:03
  • @Farmer Who knows? I just can see the short snippet of your code. In this snippet is the bug which I've spotted in my answer. The rest of the code looks fine as far as I can see. – Rabbid76 Nov 07 '20 at 20:05
  • Alright, thank you for helping, it is greatly appreciated. –  Nov 07 '20 at 20:08