【问题标题】:Collision with enemy in pygame making player lose multiple lives在pygame中与敌人碰撞使玩家失去多条生命
【发布时间】:2021-04-20 17:37:57
【问题描述】:

我正在努力做到这一点,当敌人与玩家发生碰撞时,会失去一条生命,并且玩家会被定位在屏幕的中心。它在大约一半的时间里有效,但在另一半的时间里,一次碰撞会失去两三个人的生命。

def collide(self):
        for enemy in enemies:
            if ((robot.hitbox[0] < enemy.x + 16 < robot.hitbox[0] + robot.hitbox[2]) or (robot.hitbox[0] < enemy.x - 16 < robot.hitbox[0] + robot.hitbox[2])) and ((robot.hitbox[1] < enemy.y + 16  < robot.hitbox[1] + robot.hitbox[3]) or (robot.hitbox[1] < enemy.y - 16  < robot.hitbox[1] + robot.hitbox[3])):
                robot.alive = False
                robot.x = 400
                robot.y = 300
                for enemy in enemies:
                    enemies.remove(enemy)
                robot.lives -= 1
                robot.alive = True

这是 Enemy 类下的一个函数,在 Enemy 的 draw 函数内部调用,在 while 循环中调用。

while running:
    ## add if robot.alive == True into loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False 

    userInput = pygame.key.get_pressed()

    if len(enemies) <= 3:
        randSpawnX = random.randint(32, 768)
        randSpawnY = random.randint(77, 568)
        if (robot.x - 100 <= randSpawnX <= robot.x + 100) or (robot.y - 100 <= randSpawnY <= robot.y + 100):
            randSpawnX = random.randint(32, 768)
            randSpawnY = random.randint(77, 568)
        else:
            enemy = Enemy(randSpawnX, randSpawnY)
            enemies.append(enemy)

    if robot.alive == True:     
        for enemy in enemies:
            enemy.move()
        robot.shoot()
        robot.movePlayer(userInput)

    drawGame()

谁能帮我弄清楚为什么会发生这种情况?我相信这是因为记录了多次碰撞,但是由于我在记录第一次命中并且在失去生命之前将机器人移动到屏幕中间,为什么会发生这种情况?

【问题讨论】:

标签: python oop pygame


【解决方案1】:

读取How do I detect collision in pygame? 并使用pygame.Rect / colliderect() 进行碰撞检测。

阅读How to remove items from a list while iterating? 并遍历列表的副本。

如果遇到碰撞,仅仅改变玩家的xy属性是不够的。您还需要更改hitbox。另外break检测到碰撞时的循环:

def collide(self):
    robot_rect = pygame.Rect(*robot.hitbox)
    for enemy in enemies[:]:
        enemy_rect = pygame.Rect(enemy.x, enemy.y, 16, 16)
        if robot_rect.colliderrect(enemy_rect):
            enemies.remove(enemy)
            robot.x, robot.y = 400, 300
            robot.hitbox[0] = robot.x
            robot.hitbox[1] = robot.y
            robot.lives -= 1
            break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2022-01-26
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多