在迭代数组时为每个元素添加延迟

时间:2017-09-05 23:09:01

标签: arrays swift for-loop sprite-kit delay

尝试使用SKLabelNode在标签上逐个显示下面的数组元素。我认为问题在于它在序列上迭代比在序列运行过程中更快,因此导致崩溃,因为self.addChild()试图再次显示“Set”而“Ready”仍在显示

我的问题是,在“设置”显示之前,如何减慢此迭代以便“就绪”可以出现和消失?

let readySetGo = ["Ready", "Set", "GO!"]
for i in readySetGo {
    newLevelLabel.text = i
    newLevelLabel.fontSize = 60

    let wait = SKAction.wait(forDuration: 2)
    let remove = SKAction.removeFromParent()
    let sequence = SKAction.sequence([wait, remove])

    newLevelLabel.run(sequence)

    self.addChild(newLevelLabel)
}

1 个答案:

答案 0 :(得分:2)

它立即进入GO的原因是因为你没有按照相同的顺序链接所有动作​​,所以你的所有阶段都在同一时间运行:

试试这个,我现在不是编译器:

let readySetGo = ["Ready", "Set", "GO!"]

newLevelLabel.fontSize = 60

let seq: [SKAction]=[]
let waitTime:TimeIneterval = 2

for i in readySetGo {

    let block = SKAction.run{
        self.newLevelLabel.text = i
    }

    let wait = SKAction.wait(forDuration: waitTime)

    seq.append(wait)
    seq.append(block)

}

let wait = SKAction.wait(forDuration: waitTime)
let remove = SKAction.removeFromParent()
seq.append(wait)
seq.append(remove)
let sequence = SKAction.sequence(seq)

newLevelLabel.run(sequence)

self.addChild(newLevelLabel)