无法弄清楚如何检查两个精灵之间的蒙版碰撞

ahe*_*m11 3 python pygame collision-detection sprite pygame-surface

我在同一组中有两个不同的精灵,变量“玩家”和“地面”。它们都是不同的类别,表面上都带有面具。这条线是他们两个班的。

self.mask = pygame.mask.from_surface(self.surface)
Run Code Online (Sandbox Code Playgroud)

其表面中使用的图像使用了“convert_alpha()”,因此其中一部分是透明的,并且蒙版应该对它们起作用。地面是几个平台,我想检查碰撞,这样我就可以将玩家保持在地面上,并在它们不在不透明部分上时让它们掉落。

if pygame.sprite.collide_mask(player,ground):
        print("collision")
else:
        print("nope")
Run Code Online (Sandbox Code Playgroud)

即使玩家精灵落在彩色地面精灵像素所在的位置,也会打印“不”。因此,“collide_mask()”的文档表示,当没有碰撞时,它返回“NoneType”。所以我尝试了这个。

if pygame.sprite.collide_mask(player,ground)!= NoneType:
        print("collision")
Run Code Online (Sandbox Code Playgroud)

无论玩家在哪里,都会打印“碰撞”(我为玩家设置了跳跃、向左和向右移动)。我昨天问了一个关于碰撞的问题,但没有得到有帮助的答案。我被告知要压缩我在问题中提交的代码,所以希望我能够很好地解释这一点,而无需发布所有 90 行。我在这里检查了很多其他问题,它们似乎都有点不同,所以我很困惑(而且相当新)。强调两个精灵都在同一组中,因此我无法让 spritecollide() 工作。

Rab*_*d76 5

精灵不仅需要mask属性,它们也需要rect属性。定义mask位掩码并rect指定精灵在屏幕上的位置。看pygame.sprite.collide_mask

\n
\n

通过测试两个精灵的位掩码是否重叠来测试两个精灵之间的碰撞。如果精灵具有遮罩属性,则将其用作遮罩,否则从精灵的图像创建遮罩。Sprite 必须具有rect属性;mask 属性是可选的。

\n
\n

如果在 s 中使用精灵,pygame.sprite.Group则每个精灵应该具有imagerect属性。pygame.sprite.Group.draw()pygame.sprite.Group.update()是由 提供的方法pygame.sprite.Group

\n

后者委托给update包含的pygame.sprite.Sprites \xe2\x80\x94 的方法,您必须实现该方法。看pygame.sprite.Group.update()

\n
\n

update()对组中的所有 Sprite调用该方法。[...]

\n
\n

前者使用包含的 s 的image和属性来绘制对象 \xe2\x80\x94 您必须确保 s具有所需的属性。看:rectpygame.sprite.Spritepygame.sprite.Spritepygame.sprite.Group.draw()

\n
\n

将包含的 Sprite 绘制到 Surface 参数。这使用Sprite.image源表面的属性,并且Sprite.rect。[...]

\n
\n
\n

最小的例子

\n

\n
import os, pygame\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\nclass SpriteObject(pygame.sprite.Sprite):\n    def __init__(self, x, y, image):\n        super().__init__()\n        self.image = image\n        self.rect = self.image.get_rect(center = (x, y))\n        self.mask = pygame.mask.from_surface(self.image)\n\npygame.init()\nclock = pygame.time.Clock()\nwindow = pygame.display.set_mode((400, 400))\nsize = window.get_size()\n\nobject_surf = pygame.image.load(\'AirPlane.png\').convert_alpha()\nobstacle_surf = pygame.image.load(\'Rocket\').convert_alpha()\n\nmoving_object = SpriteObject(0, 0, object_surf)\nobstacle = SpriteObject(size[0] // 2, size[1] // 2, obstacle_surf)\nall_sprites = pygame.sprite.Group([moving_object, obstacle])\n\nrun = True\nwhile run:\n    clock.tick(60)\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            run = False\n\n    moving_object.rect.center = pygame.mouse.get_pos()\n    collide = pygame.sprite.collide_mask(moving_object, obstacle)\n    \n    window.fill((255, 0, 0) if collide else (0, 0, 64))\n    all_sprites.draw(window)\n    pygame.display.update()\n\npygame.quit()\nexit()\n
Run Code Online (Sandbox Code Playgroud)\n