我已经想出如何每隔x秒连续生成一个节点。但是,我希望减少等待游戏继续创建节点的时间,以增加难度。例如,我在didMoveToView中调用此函数:
func createSequentialEnemies(){
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(createEnemy),
SKAction.waitForDuration(2.0)
])
))
}
这会每2秒产生一个敌人,但我想任意减少这个持续时间。例如,假设经过30秒的游戏后我想要每1.5秒产生一次敌人。我如何动态更改持续时间?
答案 0 :(得分:2)
在场景类中创建spawnDuration属性和键引用。
class SomeClass: SKScene {
private var spawnDuration: NSTimeInterval = 2.0
private let spawnKey = "SpawnKey"
}
比调整产生代码以使用此spawn属性和键。我稍微改变了语法,使其在我看来更清晰。
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)
}
希望这有帮助