错误地以正确的顺序删除精灵组敌人。

问题描述 投票:1回答:1

我有两个精灵组,一个是敌人,一个是玩家的武器。例如我如何设置敌人的精灵组...... (武器的精灵组也是这样做的)

class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time):
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.const = const
        self.dash_counter = dash_counter
        self.dash = dash
        self.dash_time = dash_time
        self.fly_count = fly_count
        self.fly_time = fly_time
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y
    def update(self):
        if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
            self.bat_health -= 1 
        if self.bat_health == 0:
            self.kill()
        ... #Irrelevant
all_bats = pygame.sprite.Group()

def bat_create():
    bat_x = r_x*40
    bat_y = r_y*40
    bat_health = 5
    bat_immune = False
    const = 3
    dash_counter = 0
    dash = False
    dash_time = 0
    fly_count = 0
    fly_time = 0
    new_bat = Bat(bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time)
    all_bats.add(new_bat)

当玩家的武器击中蝙蝠时,不管是哪只蝙蝠被击中,在5次击中后,第一个产生的蝙蝠都会被杀死。我不知道为什么会发生这种情况。

python class pygame sprite collision-detection
1个回答
1
投票

看起来这就是问题所在。

def update(self):
    if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
        self.bat_health -= 1 

groupcollide 返回一个碰撞的列表 上面的代码正在检查 all_bats 与...对抗 all_swords所以,一切VS一切。而 if ( non-empty-list ) 总是返回 True.

所以如果 任何 蝙蝠+剑的碰撞,这个精灵的健康是减少的。 这可能是减少 每一 蝙蝠 self.bat_health 每次 任何 蝙蝠碰撞。 因此,第一个创建的物品将首先达到零。

你需要检查 "这个精灵 "是否是碰撞的一部分。 这是个相当简单的变化。

def update(self):
    hit_list = pygame.sprite.groupcollide(all_bats, all_sword, False, True):
    if ( self in hit_list ):
        self.bat_health -= 1 

但是做一个 groupcollide 每只蝙蝠,在每只蝙蝠的 update(). 也许是移动 groupcollide 打到外地 .update() 函数,并只需执行一次这些计算。 将碰撞结果传给sprite-update函数,或者类似的函数。

© www.soinside.com 2019 - 2024. All rights reserved.