一定时间后停止 SKAction

Stop SKAction after a certain amount of time

我的游戏中有许多敌人在不同的时间生成,并使用 SKAction 移动,但在每个关卡结束时我都有一个生成的 Boss。当 Boss 生成时,我希望其他敌人停止产卵。我对每个敌人都有一个功能。我在每个敌人的 SKAction.sequence 中使用 withKey:,然后在 boss 函数中使用 removeAction(forKey: ) 来阻止它,但它不起作用。我是不是用错了。

我的代码示例(只留在 SKAction 代码中,删除了所有其他代码)

override func didMove(to view: SKView) {
       //Spawn Enemy1
        run(SKAction.repeatForever(
          SKAction.sequence([SKAction.run() { [weak self] in
                              self?.addEnemy1()
                            },
                            SKAction.wait(forDuration: 5.0)])))

}

func addEnemy1() {
        
        let delay = SKAction.wait(forDuration: 10)
        let actionMove = SKAction.moveTo(y: -600, duration: 5.0)
        let actionRemove = SKAction.removeFromParent()
        enemy1.run(SKAction.sequence([delay, actionMove, actionRemove]), withKey:"enemy1")
        
    }

func addBoss() {
        
        let move1 = SKAction.moveTo(y: size.height / 3.5, duration: 3)
        let move2 = SKAction.moveTo(x: size.width / 3, duration: 3)
        let move3 = SKAction.moveTo(x: 0 - boss.size.width, duration: 3)
        let move4 = SKAction.moveTo(x: 0, duration: 1.5)
        let move5 = SKAction.fadeOut(withDuration: 0.2)
        let move6 = SKAction.fadeIn(withDuration: 0.2)
        let move7 = SKAction.moveTo(y: 0 - boss.size.height * 3, duration: 3)
        let move8 = SKAction.moveTo(y: size.height / 3.5, duration: 3)

        let action = SKAction.repeat(SKAction.sequence([move5, move6]), count: 6)
        let repeatForever = SKAction.repeatForever(SKAction.sequence([move2, move3, move4, action, move7, move8]))
        let sequence = SKAction.sequence([move1, repeatForever])

        boss.run(sequence)
        
        enemy1.removeAction(forKey: "enemy1")
    }

您正在删除错误的操作。键为“enemy1”的操作是:

SKAction.sequence([delay, actionMove, actionRemove])

这只是让敌人动起来。删除它只会暂时停止这一系列操作。再次调用addEnemy1时,再次添加动作序列。

生成敌人的动作是您在 self 上 运行 的动作:

    run(SKAction.repeatForever(
      SKAction.sequence([SKAction.run() { [weak self] in
                          self?.addEnemy1()
                        },
                        SKAction.wait(forDuration: 5.0)])))

你应该给那个动作一个键:

...
},
SKAction.wait(forDuration: 5.0)])), withKey: "spawnEnemy")

然后从 self 中删除:

removeAction(forKey: "spawnEnemy")