如何将玩家图像放在另一个图像前面?
我有一段代码运行得很好,但唯一的问题是玩家的图像在其他图像后面,所以你看不到玩家在哪里。我该怎么做才能让玩家的图像在其他图像前面,就像是背景层一样?还有,我怎么才能让其他图像出现在其他背景图像的后面?比如说,我有一棵背景树:
class Tree(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('tree.png')
self.rect = self.image.get_rect()
还有我有玩家的类:
class Player(pygame.sprite.Sprite):
change_x = 0
change_y = 0
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('mapMover.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def changespeed_x(self,x):
self.change_x = x
def changespeed_y(self,y):
self.change_y = y
def update(self, barrier_list, Upcar_list, Downcar_list):
self.rect.x += self.change_x
barrier_hit_list = pygame.sprite.spritecollide(self, barrier_list, False)
Upcar_hit_list = pygame.sprite.spritecollide(self, Upcar_list, False)
Downcar_hit_list = pygame.sprite.spritecollide(self, Downcar_list, False)
for barrier in barrier_hit_list:
if self.change_x > 0:
self.rect.right = barrier.rect.left
else:
self.rect.left = barrier.rect.right
for Upcar in Upcar_hit_list:
if self.change_x > 0:
self.rect.right = Upcar.rect.left
Upcar.rect.x += 3
else:
self.rect.left = Upcar.rect.right
Upcar.rect.x -= 3
return
for Downcar in Downcar_hit_list:
if self.change_x > 0:
self.rect.right = Downcar.rect.left
Downcar.rect.x += 3
else:
self.rect.left = Downcar.rect.right
Downcar.rect.x -= 3
return
self.rect.y += self.change_y
barrier_hit_list = pygame.sprite.spritecollide(self, barrier_list, False)
Upcar_hit_list = pygame.sprite.spritecollide(self, Upcar_list, False)
Downcar_hit_list = pygame.sprite.spritecollide(self, Downcar_list, False)
for barrier in barrier_hit_list:
if self.change_y > 0:
self.rect.bottom = barrier.rect.top
else:
self.rect.top = barrier.rect.bottom
for Upcar in Upcar_hit_list:
if self.change_y > 0:
self.rect.top = Upcar.rect.bottom
Upcar.rect.y += 3
else:
self.rect.bottom = Upcar.rect.top
Upcar.rect.x -= 3
return
for Downcar in Downcar_hit_list:
if self.change_y > 0:
self.rect.top = Downcar.rect.bottom
Downcar.rect.y += 3
else:
self.rect.bottom = Downcar.rect.top
Downcar.rect.x -= 3
return
Python 2.6,Pygame Sprites,Windows 7
2 个回答
4
你没有展示相关的代码,但问题很明显:
你最后绘制到屏幕上的Surface
是“在最上面”的。如果你先画你的角色精灵,然后再把背景图画在它上面,你只会看到背景图。
所以你要么得按照正确的顺序来绘制你的精灵,要么因为你使用了Sprite
类,可以把你的精灵放到一个LayeredUpdates
组里,并给它们一个_layer
属性。
2
如上所述,你在主循环中先画玩家,然后再画背景。
错误:
while not done: # The main loop, it may be different in your code.
player.draw()
background.draw() # What you're probably doing.
正确:
while not done: # The main loop, it may be different in your code.
background.draw() # What you should do.
player.draw()
为了确保无误,无论你是怎么实现的,都要在主循环的开始部分之后,立刻画出背景。如果你在一个单独的程序里更新或绘制你的游戏,比如:
def update():
background.draw() # What you should do.
player.draw()
while not done:
update()
一定要确保在这个单独的函数里,背景是最先被画出来的。记住:背景(BACKground),你应该总是把它放在其他东西的“后面”(之前/之前):).