下面的代码绘制了黑色背景,白色框和文本。但是,似乎绘图顺序没有确定,我有时会将文本或矩形覆盖在背景矩形中。我试图了解管理它的适当方法是什么?
import sdl2.ext
import sdl2.sdlttf
from sdl2 import SDL_Color, SDL_Init
WHITE = SDL_Color(255, 255, 255)
class Entity(sdl2.ext.Entity):
def __init__(self, world, sprite, posx=0, posy=0):
self.sprite = sprite
self.sprite.position = posx, posy
sdl2.ext.init()
window = sdl2.ext.Window("PySDL2", size=(320, 240))
window.show()
world = sdl2.ext.World()
texture_renderer = sdl2.ext.Renderer(window)
spriterenderer = sdl2.ext.TextureSpriteRenderSystem(texture_renderer)
factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE, renderer=texture_renderer)
world.add_system(spriterenderer)
sdl2.sdlttf.TTF_Init()
font = sdl2.sdlttf.TTF_OpenFont('resources/Helvetica.dfont',32)
text_surface = sdl2.sdlttf.TTF_RenderText_Blended(font, 'test', WHITE).contents
sdl2.sdlttf.TTF_CloseFont(font)
bg = factory.from_color(sdl2.ext.Color(0, 0, 0), size = (320,240))
Entity(world, bg, 0, 0)
c = factory.from_color(sdl2.ext.Color(255, 255, 255), size = (50,50))
Entity(world, c, 100, 100)
text_sprite = factory.from_surface(text_surface)
text_entity = Entity(world, text_sprite, 50, 50)
def run():
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
world.process()
run()
sdl2.ext.quit()
答案 0 :(得分:0)
TextureSpriteRenderSystem
的默认实现使用depth
对象的Sprite
属性来确定绘图顺序。如果所有精灵都具有相同的深度,则它们的绘制顺序是不确定的,这会导致您的不良行为。
深度值为0的Sprite
将在具有更高深度值的Sprite
下方(或之前)绘制,例如10.创建的每个Sprite
的默认深度为0.您可以将背景和矩形的depth
设置为负值,以强制执行绘图顺序:
bg = factory.from_color(sdl2.ext.Color(0, 0, 0), size = (320,240))
bg.depth = -99 # always below everything
Entity(world, bg, 0, 0)
c = factory.from_color(sdl2.ext.Color(255, 255, 255), size = (50,50))
c.depth = -1
Entity(world, c, 100, 100)
您可以在PySDL2 sprite documentation中了解更多相关信息。