Python Pygame表面层:透明精灵层问题
我正在使用Python Pygame表面层:透明精灵层问题,python,pygame,Python,Pygame,我正在使用surface.fill(color,rect)在精灵曲面上绘制一个小的彩色正方形,然后按以下顺序显示在其他曲面的顶部: 背景面 迷宫曲面 雪碧表面 目前我有一个问题,我的精灵涂抹在屏幕上,因为我没有每次擦拭屏幕如何消除这种涂抹效果,同时防止精灵层覆盖其他层? 层代码-已初始化,但未更新每个帧。 game_surface = pygame.Surface((self.canvas.get_size())) game_surface = game_surface.convert() ga
surface.fill(color,rect)
在精灵曲面上绘制一个小的彩色正方形,然后按以下顺序显示在其他曲面的顶部:
game_surface = pygame.Surface((self.canvas.get_size()))
game_surface = game_surface.convert()
game_surface.fill((0,0,255))
maze_surface = pygame.Surface((self.canvas.get_size()))
maze_surface = maze_surface.convert_alpha()
maze_surface.fill((0,0,255,0))
play_surface = pygame.Surface((self.canvas.get_size()))
play_surface = play_surface.convert_alpha()
play_surface.fill((0,0,0,0))
def update(self, canvas):
# move sprite if keys pressed (not shown)
self.surface.fill((0,0,0,0)) # Newest screen fill attempt. Causes smearing effect
self.surface.fill(self.color, self.rect) # draw green square
canvas.blit(self.surface, (0,0))
目前只有play_曲面
实际使用透明度,但最终play_曲面
和maze_曲面
都需要透明
精灵层更新-每次移动精灵时调用。
game_surface = pygame.Surface((self.canvas.get_size()))
game_surface = game_surface.convert()
game_surface.fill((0,0,255))
maze_surface = pygame.Surface((self.canvas.get_size()))
maze_surface = maze_surface.convert_alpha()
maze_surface.fill((0,0,255,0))
play_surface = pygame.Surface((self.canvas.get_size()))
play_surface = play_surface.convert_alpha()
play_surface.fill((0,0,0,0))
def update(self, canvas):
# move sprite if keys pressed (not shown)
self.surface.fill((0,0,0,0)) # Newest screen fill attempt. Causes smearing effect
self.surface.fill(self.color, self.rect) # draw green square
canvas.blit(self.surface, (0,0))
涂抹效果:红色=迷宫层
,绿色=涂抹精灵
替代精灵填充-上述更改版本
def update(self, canvas):
# move sprite if keys pressed (not shown)
self.surface.fill((0,0,0)) # Original screen fill. Covers up lower layers
self.surface.fill(self.color, self.rect) # draw green square
canvas.blit(self.surface, (0,0))
非透明-黑色=填充颜色(我希望在不覆盖其他层的情况下进行此操作)
如何消除这种涂抹效果(图1),同时防止精灵层覆盖其他层(图2)?非常感谢您的帮助。您需要重新绘制精灵覆盖的背景,更新其位置,然后在新位置重新绘制精灵 您可能对探索内置支持此功能的
pygame.sprite
模块感兴趣。您可以创建pygame.sprite.sprite
的子类:
更新(自)
方法(可选)self.image
和self.rect
属性pygame.sprite.Group
实例中Pygame的精灵组类(如
group
、GroupSingle
、LayeredUpdates
等)包括Pygame.sprite.group.clear(surface\dest,background)
(请参阅)等方法,以便在移动精灵并将其重新绘制到其他位置之前,在精灵上重新绘制背景图像 我希望有一种方法可以做到这一点,而不必在每一帧都重新绘制背景,因为背景不会改变,重新绘制它是多余的。Pygame显示器表面已经在背景的一部分上绘制了精灵,因此在某个点上,必须再次在那里绘制背景。但是,这可以通过只重绘每个精灵下的区域而不是整个屏幕来优化。我提到的pygame.sprite.Group.clear
方法只会重新绘制组中每个pygame.sprite
的rect
属性下的区域,这可能会有所帮助。我试图创建sprite
组和对象,但我得到的错误是“Player”对象没有属性“image”
。我不想使用图像来表示精灵,这就是我使用fill
方法的原因。你知道我如何在不指定image
属性的情况下绘制精灵吗?我认为pygame.sprite
模块不支持这种自定义绘制。您可能只需要维护一个rect
属性,并对精灵使用self.image=None
。然后您可以使用其他功能,并使用自己的系统处理绘图。就我所知,使用sprite.Group.clear
会导致我的绘图功能中断或工作不正常。屏幕清除,但精灵不绘制(只是一个红色屏幕)。