改变精灵的可见性而不改变它在精灵组中的位置
Changing the visibility of a sprite without changing it's position in the sprite group
我有两个精灵组:visible_ui_elements
和 ui_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 被设置为不可见,但随后再次显示,它在 sprite 组中的位置将被置于该组的前面,而不是之前的位置。这显然会导致精灵的分层不正确。
您可以尝试使用管理图层绘制的精灵组。请参阅 pygame.sprite.LayeredUpdates
here.
的文档
添加的顺序不仅仅与精灵所在的层有关。您可以更改图层以在绘制顺序中向上或向下移动它们,以便您想要的在最上面。
然后您将他们添加到组中的顺序将无关紧要。
我有两个精灵组:visible_ui_elements
和 ui_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 被设置为不可见,但随后再次显示,它在 sprite 组中的位置将被置于该组的前面,而不是之前的位置。这显然会导致精灵的分层不正确。
您可以尝试使用管理图层绘制的精灵组。请参阅 pygame.sprite.LayeredUpdates
here.
添加的顺序不仅仅与精灵所在的层有关。您可以更改图层以在绘制顺序中向上或向下移动它们,以便您想要的在最上面。
然后您将他们添加到组中的顺序将无关紧要。