3
\$\begingroup\$

I have been trying to make a game, but mask collision doesn't seem to work. Here is my code:

    class Player(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.all_sprites
                    pg.sprite.Sprite.__init__(self.groups)
                    #nothing else important

            def update(self):
                    self.mask = pg.mask.from_surface(self.image)
                    #check if hits
                    hits = pg.sprite.spritecollide(self, self.game.kill, False, pg.sprite.collide_mask)
                    if hits:
                            #stops game
                            self.game.playing = False

    class Kill(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.kill
                    pg.sprite.Sprite.__init__(self.groups)
            def update(self):
                    self.mask = pg.mask.from_surface(self.image)

The problem is that the game sets self.game.playing to False even before the pixels collide.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Please add a description of the problem, including what you mean by "don't work", what you expect to happen, what actually happens and what you have tried. \$\endgroup\$ Feb 11 '18 at 12:14
  • \$\begingroup\$ sorry for late answere but, In the real game I have time.sleep(1) to see when the sprites hit. Then I see that the collistion is way off on sprites like spikes \$\endgroup\$
    – KMuJu
    Feb 16 '18 at 16:16
  • \$\begingroup\$ You have an extra underscore before __init__, that means the __init__ methods won't be called during the instantiation (the code shouldn't work at all because of this typo). Please elaborate the question. \$\endgroup\$
    – skrx
    Apr 25 '18 at 20:46
0
\$\begingroup\$

You might want to try directly using the collide_mask() method of the Sprite class. Like you, I have had issues trying to use it as an argument in the spritecollide() method.

Also, as a rule, you should do regular rectangle collision testing before you test for mask collisions, and only test mask collisions in the event of a rectangular collision. This is because mask collision testing is expensive, but rectangle collision testing is cheap.

I might do something like this:

for sprite in self.game.kill:

    # regular collision check before mask collision check for efficiency
    if self.bounding_rect.colliderect(sprite.bounding_rect):

        # mask collision check
        if pg.sprite.collide_mask(self, sprite):
            self.game.playing = False
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .