简体   繁体   English

用pygame动态控制精灵blit顺序

[英]Dynamically controlling sprite blit order with pygame

I'm currently writing a Tower Defence game. 我目前正在写《塔防》游戏。 Everything works fine but there's a visual issue that's bugging me. 一切正常,但是有一个视觉问题困扰着我。

Basically, a sprite that has a lower rect.y and should be higher on the map to pass behind a slower mob with a higher rect.y , can be blitted after (and therefore in front of) the foreground sprite. 基本上,具有较低rect.y且应在地图上较高的rect.y可以在前景精灵之后 (并因此在其前面)被rect.y ,以便在具有较高rect.y的较慢rect.y 之后传递。

I could fix it, but not while keeping the random spread-out spawn points that I like. 我可以修复它,但不能同时保留我喜欢的随机散布生成点。

Could anybody suggest anything to help? 有人可以提出任何帮助的建议吗? I omitted irrelevant code, so there's not much to sift through. 我省略了无关的代码,因此没有太多需要筛选的内容。

class Pokemon(pygame.sprite.Sprite):
    def __init__(self, name, health, speed, attack, typeOf, typeOf2, level, order):
        pygame.sprite.Sprite.__init__(self)
        self.order = order
        self.image = pygame.image.load('C:/Users/#/#/#/pygames/tower_defense/Distributable/images/POKEMON/%sright.png'%(name))

        self.rect = self.image.get_rect()
        # X/Y axis locations
        self.rect.centerx = 0-self.rect.width - self.order*100
        self.rect.centery = random.randint(500, 540)

Then the creation block - 然后创建块-

for e in range(numberOfEnemies):
    poke = random.randint(1, 2)
    if poke == 1:
        level = random.randint(2, 5)
        Pidgey = Pokemon('Pidgey', 15, 2, 5, 'Normal', 'Flying', level, e)
        enemies.append(Pidgey)
        enemy_sprites.add(Pidgey)
    else:
        level = random.randint(2, 4)
        Rattata = Pokemon('Rattata', 13, 3, 5, 'Normal', None, level, e)
        enemies.append(Rattata)
        enemy_sprites.add(Rattata)
    enemyNumber += 1

If you need to control the layers of the sprites, you can use a LayeredUpdates sprite group. 如果需要控制子画面的图层,则可以使用LayeredUpdates子画面组。 The sprites need a self._layer attribute or you can pass the layer when you add the sprite to the group, eg: 子画面需要self._layer属性,或者在add子画面add到组中时可以传递图层,例如:

layered_group.add(sprite, layer=desired_layer)

When a sprite is moved, you can call the change_layer method of the sprite group: 移动精灵时,可以调用精灵组的change_layer方法:

layered_group.change_layer(sprite, sprite.rect.bottom)

However, if you have to update the layers of all sprites each frame, it would be more efficient to sort the sprites by their rect.bottom position, iterate over the list and blit them: 但是,如果必须每帧更新所有子画面的图层,则按其rect.bottom位置rect.bottom进行排序,遍历列表并对其进行blit会更有效。

blit = screen.blit  # Local variable to improve the performance.
for sprite in sorted(all_sprites, key=lambda spr: spr.rect.bottom):
    blit(sprite.image, sprite.rect)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM