更新内部多次快速调用函数

时间:2017-11-28 19:03:14

标签: swift function sprite-kit

我通过SpriteKit创建游戏。在游戏中,每隔几秒就有一个球产生到屏幕上(通过功能),玩家必须将它们炸掉。现在,我想通过他的分数检查玩家等级,所以如果分数大于10,spawnBall功能将被执行两次(因此2个球将在屏幕上产生),依此类推。我尝试通过更新乐趣(将“读取”玩家得分并取决于得分将调用spawnBall函数)。不幸的是,当我这样做时,屏幕会在几秒钟内产生数百万个(或者说是)球(正如我所说,我希望它每隔几秒就调用一次这个功能,并在分数为X时增加通话)。我真的不知道该怎么做。 这是我的代码:

override func update(_ currentTime: CFTimeInterval) {

    if (self.score <= 10){
        spawnBalls()
    }

    if (self.score > 10 && self.score <= 20){
        spawnBalls()
        spawnBalls()
    }

    if (self.score > 20){
        spawnBalls()
        spawnBalls()
        spawnBalls()
    }

    if (self.subscore == 3) {
        _ = randomBallColorToBlow()
        self.subscore = 0
    }
}

func spawnBalls() {
    let wait = SKAction.wait(forDuration: 1)
    let action = SKAction.run {
        self.createBall()
    }
    run(SKAction.repeatForever((SKAction.sequence([wait, action]))))
}

如何在不使用更新功能的情况下完成?

2 个答案:

答案 0 :(得分:2)

你通过在更新功能中调用它来每秒调用60次产卵球。 尝试检查是否满足某个要求,以便在更新中升级到更高的生成率,但保持调用不在更新函数中。

private var upgradedToLevel2 = false
private var upgradedToLevel3 = false

//called somewhere probably in a start game func
spawnBalls(duration: 1.0)

override func update(_ currentTime: CFTimeInterval) {

    if (self.score > 10 && self.score <= 20) && !upgradedToLevel2 {
        //this prevents the if loop from running more than once
        upgradedToLevel2 = true 
        self.removeAction(forKey: "spawn")
        spawnBalls(duration: 0.5)
    }

    if (self.score > 20) && !upgradedToLevel3 {
        //this prevents the if loop from running more than once
        upgradedToLevel3 = true
        spawnBalls(duration: 0.33)
    }
}

func spawnBalls(duration: Double) {

    let wait = SKAction.wait(forDuration: duration)
    let action = SKAction.run { self.createBall() }
    let repeater = SKAction.repeatForever(SKAction.sequence([wait, action]))

    run(repeater, withKey: "spawn")
}

答案 1 :(得分:1)

如前所述,你会多次产生球,需要将其分解。我建议使用Int而不是bool来跟踪关卡,以便能够处理“无限”数量的级别而不会产生“无限”的布尔变量

private var nextLevel = 0 //Level 0 allows us to spawn a ball on startup, so no need to call spawnBalls anywhere else

override func update(_ currentTime: CFTimeInterval) {

    if (self.score > 10 * nextLevel){
        self.removeAction(forKey: "spawn") //this prevents the if loop from running more than once
        nextLevel += 1
        spawnBalls(count:nextLevel,forDuration:1) //You can change the 1 here if you want to spawn balls at a faster speed,  I would recommend a variable that uses nextLevel in a forumula
    }
}

func spawnBalls(count:Int, forDuration duration:TimeInterval) {
    let range = 0..<count
    let wait = SKAction.wait(forDuration: duration)
    let action = SKAction.run {range.forEach{self.createBall()}}
    let repeater = SKAction.repeatForever(SKAction.sequence([wait, action]))
    removeAction(forKey:"spawn")
    run(repeater, withKey: "spawn")
}