【问题标题】:Pygame mask collisions not detected even with offsets at zero即使偏移量为零,也未检测到 Pygame 掩码冲突
【发布时间】:2020-05-31 04:41:12
【问题描述】:

我正在使用 pygame 编写游戏。滑雪者对象在 x 轴上左右移动,而树对象在 y 轴上在屏幕上向上移动。从提取的代码外部,调用 Tree 类方法 collide 传递对象树和滑雪者(即Tree.collide(tree,skier))。我已经修改了 collide 方法,以便它打印 x 和 y 偏移量以及是否满足碰撞测试(即ret_mask none)。将基础程序限制为一个滑雪者和一棵具有相同 x 坐标的树,我看到树直接穿过滑雪者,生成打印的 offset_xoffset_y 为零,但仍然得到 ret_mask None 即使树木完全穿过滑雪者并在 y 轴上离开屏幕。查看一些较旧的代码,我尝试在加载 PNG 时添加 .convert() 并设置 colorkey(white) - 如 cmets 所示。但是,这并没有什么不同。

非常感谢任何关于我为什么没有遇到碰撞的帮助!

# Load Image PNGs
white=(255, 255, 255) #added definition of white
SKIER=pygame.image.load(os.path.join('assets','skier_img.png')).convert() #added .convert() to end
SKIER.set_colorkey(white) #added line
TREE=pygame.image.load(os.path.join('assets','tree_img.png')).convert() #added .convert() to end
SKIER.set_colorkey(white) #added line


# Define Object Classes
class Sprite:
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.img=None

class Skier(Sprite):
    def __init__(self,x,y):
        super().__init__(x,y)
        self.img=SKIER
        self.mask=pygame.mask.from_surface(self.img)

class Tree(Sprite):
    def __init__(self,x,y):
        super().__init__(x,y)
        self.img=TREE
        self.mask=pygame.mask.from_surface(self.img)

    def move(self,vel):
        self.y-=vel

    def collide(obj1,obj2):
        offset_x=obj2.x-obj1.x
        offset_y=obj2.y-obj1.y
        ret_mask=obj1.mask.overlap(obj2.mask,(offset_x,offset_y))
        if (obj1.mask.overlap(obj2.mask,(offset_x,offset_y)) != None):
            print('Collision Detected!')
        else:
            print(f'offset_x is {offset_x} and offset_y is {offset_y} and mask output is {ret_mask}')

【问题讨论】:

    标签: python-3.x pygame collision mask


    【解决方案1】:

    对不起大家!我解决了。 实际上,我使用 .convert() 方法和 set_colorkey(white) 所采取的步骤确实有效。 只是由于进行复制和粘贴,我的代码中有一个错误:我在 SKIER 上设置了两次颜色键,而不是在树上。 另外,非常感谢 Rabbid76 正确地重新格式化了我的问题中的代码 - 抱歉我匆忙发布。 总体而言,在荣耀中掩饰自己的得分为零....

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2013-03-06
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多