如何在Swift中更改Spritekit操作中的变量?

时间:2017-08-24 18:17:40

标签: swift variables sprite-kit

我正在尝试实施一系列包含"等待"变量随着分数的增加而变化。我无法弄清楚我做错了什么,但是我尝试生成的对象会在等待时间相同的等待时间内产生,即使等待变量减少也是如此。这是我的产卵功能:

func spawn() {
    var waitDuration = TimeInterval(3.5)

    let setWaitDuration = SKAction.run({
        () in

        switch self.score {
        case 0..<5:
            waitDuration = 3.5
        case 5..<12:
            waitDuration = 2
        case 12..<25:
            waitDuration = 1
        case 25..<40:
            waitDuration = 1.7
        case 40..<60:
            waitDuration = 1.4
        case 60..<80:
            waitDuration = 1.2
        default:
            waitDuration = 1.0
        }
    })

    let wait = SKAction.wait(forDuration: waitDuration, withRange: 0.5)
    let spawn = SKAction.run(createAsteroid)
    let spawnSequence = SKAction.sequence([spawn, setWaitDuration, wait])
    run(SKAction.repeatForever(spawnSequence), withKey: "actionKey")
}

1 个答案:

答案 0 :(得分:0)

你永远不会回想起spawn()因此等待变量永远不会改变。在第一次运行此func时,将使用score变量设置创建运行操作。该操作将以该分数保存,并且永远不会更改。

您可以使用递归来解决此问题。并让动作只调用func,这样就可以正确设置waitDuration

func spawn() {

    var waitDuration: Double!

    switch self.score {

        case 0..<5:
            waitDuration = 3.5
        case 5..<12:
            waitDuration = 2
        case 12..<25:
            waitDuration = 1
        case 25..<40:
            waitDuration = 1.7
        case 40..<60:
            waitDuration = 1.4
        case 60..<80:
            waitDuration = 1.2
        default:
            waitDuration = 1.0
    }

    let wait = SKAction.wait(forDuration: waitDuration, withRange: 0.5)
    let spawn = SKAction.run(createAsteroid)
    let rerun = SKAction.run { self.spawn() }
    let spawnSequence = SKAction.sequence([spawn, wait, rerun])
    run(spawnSequence, withKey: "actionKey")
}
  

编辑已删除重复