【问题标题】:swift spritekit increase frequency of node creation as time goes onswift spritekit 随着时间的推移增加节点创建的频率
【发布时间】:2016-12-22 07:27:05
【问题描述】:

我已经弄清楚如何每 x 秒连续生成一个节点。但是,我想随着游戏的进行减少等待创建节点的时间,以增加难度。比如我在didMoveToView中调用了这个函数:

func createSequentialEnemies(){
    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(createEnemy),
            SKAction.waitForDuration(2.0)
            ])
        ))
}

这会每 2 秒创建一个敌人,但我想任意减少此持续时间。例如,假设在玩了 30 秒后,我想现在每 1.5 秒生成一次敌人。如何动态更改持续时间?

【问题讨论】:

    标签: swift skaction


    【解决方案1】:

    在您的场景类中创建 spawnDuration 属性和键引用。

    class SomeClass: SKScene {
    
           private var spawnDuration: NSTimeInterval = 2.0
           private let spawnKey = "SpawnKey"
    
    }
    

    调整您的生成代码以使用此生成属性和密钥。在我看来,我还稍微更改了语法以使其更易读。

    func createSequentialEnemies(){
          removeActionForKey(spawnKey) // remove previous action if running. This way you can adjust the spawn duration property and call this method again and it will cancel previous action.
    
          let spawnAction = SKAction.runBlock(createEnemy)
          let spawnDelay = SKAction.waitForDuration(spawnDuration)
          let spawnSequence = SKAction.sequence([spawnAction, spawnDelay])
          runAction(SKAction.repeatActionForever(spawnSequence), withKey: spawnKey) // run action with key so you can cancel it later
    }
    

    您必须添加一些关于何时更改您创建的生成持续时间属性的逻辑。

    基于时间的函数可以是这样的函数,您也可以在 DidMoveToView 中调用一次

     func startDifficultyTimer() {
    
         let difficultyTimerKey = "DifficultyTimerKey"
    
         let action1 = SKAction.waitForDuration(30)
         let action2 = SKAction.runBlock { [unowned self] in
    
              guard self.spawnDuration > 0.2 else {  // set a min limit
                  removeActionForKey(difficultyTimerKey) // if min duration has been reached than you might as well stop running this timer.
                  return 
              } 
    
              self.spawnDuration -= 0.5 // reduce by half a second
              self.createSequentialEnemies() // spawn enemies again
    
         }
         let sequence = SKAction.sequence([action1, action2])
         runAction(SKAction.repeatActionForever(sequence), withKey: difficultyTimerKey)
     }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 2015-06-01
      • 2013-08-30
      • 2011-10-21
      • 2011-03-07
      • 2013-08-10
      相关资源
      最近更新 更多