更改精灵的可见性而不更改其在精灵组中的位置

问题描述

我有两个精灵组:visible_ui_elementsui_elements。仅渲染visible_ui_elements中的精灵。我正在使用set_visible方法来更改子画面的可见性。

class UIMain:

    ui_elements = pg.sprite.Group()
    visible_ui_elements = pg.sprite.Group()


class UIComponent(pg.sprite.Sprite):

   def __init__(self):
       pg.sprite.Sprite.__init__(self)
 
       UIMain.visible_ui_elements.add(self)
       UIMain.ui_elements.add(self)

    def set_visible(self,visibility=False):
        """
        Changes the visibility of this component

        :param visibility: Set to true to make this component visible
        :return: None
        """
        if visibility:
            UIMain.visible_ui_elements.add(self)
        else:
            UIMain.visible_ui_elements.remove(self)

我遇到的问题是,如果一个精灵被设置为不可见,但后来又变得可见,则它在精灵组中的位置将被置于该组的最前面,而不是之前的位置。显然,这会导致精灵的分层不正确。

解决方法

您可以尝试使用管理图层绘制的Sprite组。请参阅pygame.sprite.LayeredUpdates here的文档。

添加顺序不仅会覆盖精灵所在的图层。您可以更改图层以按绘制顺序将其向上或向下移动,以便将所需的图层置于顶部。

那么您在组中添加它们的顺序就没关系了。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...