How can I made a collision mask?

若如初见. 提交于 2020-06-22 04:10:49

问题


I try to make a collision mask to detect if two sprites collide themselves, but It's not working at all, I got an instant crash, Can you help me ?

My code is :

        Player.rect = Player.image.get_rect()
        oc1.rect = oc1.image.get_rect()
        mask_1 = pg.mask.from_surface(Player)
        mask_2 = pg.mask.from_surface(oc1)
        Cm = pg.sprite.collide_mask(mask_1, mask_2)
        if Cm != None :
            print('life - 1')

回答1:


See the documentation of pygame.sprite.collide_mask():

Collision detection between two sprites, using masks.

collide_mask(SpriteLeft, SpriteRight) -> point

Tests for collision between two sprites, by testing if their bitmasks overlap. If the sprites have a "mask" attribute, that is used as the mask, otherwise a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a "rect" and an optional "mask" attribute.

The parameters to .collide_mask() have to be 2 pygame.sprite.Sprite objects, rather than 2 mask pygame.mask.Mask objects:

In the following is assumed, that Player and oc1 are pygame.sprite.Sprite objects:

Player.rect = Player.image.get_rect()
oc1.rect = oc1.image.get_rect()

Cm = pg.sprite.collide_mask(Player, oc1)

if Cm != None :
    print('life - 1')


来源:https://stackoverflow.com/questions/56043600/how-can-i-made-a-collision-mask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!