我非常了解 SKAction API,但在多个节点上运行顺序代码时我无法获得良好的代码。
这是示例代码(简化):
import SpriteKit
class GameScene: SKScene {
weak var node1: SKNode!
weak var node2: SKNode!
override func didMove(to view: SKView) {
super.didMove(to: view)
cacheUI()
runSampleSequence()
}
private func cacheUI() {
// Fetch nodes from associated SKS file
node1 = self.childNode(withName: "node1")!
node2 = self.childNode(withName: "node2")!
}
private func runSampleSequence() {
// I want node1 to fadeIn
// then node2 to fadeIn
// then node1 to fadeOut
// then node2 to fadeOut
node1.run(SKAction.sequence([
SKAction.fadeIn(withDuration: 1),
SKaction.run { [weak self] in
self.node2.run(SKAction.fadeIn(withDuration: 2))
},
SKAction.fadeOut(withDuration: 4),
SKaction.run { [weak self] in
self.node2.run(SKAction.fadeOut(withDuration: 3))
}
]))
}
}
前面的代码将完美运行,但如果我们添加node3、node4,则会生成样板代码......我希望能够重构它,以便更容易阅读和维护给定的规范。就像是 :
// Does not compile
self.run(SKAction.sequence([
node1.fadeIn(withDuration: 1),
node2.fadeIn(withDuration: 2),
node1.fadeOut(withDuration: 4),
node2.fadeOut(withDuration: 3)
]))
我能实现这个目标吗?我希望业务代码看起来尽可能清晰。
使用 SKAction.run { _ } 时,SKAction.sequence(_:) 的行为如何,是否保证在最后一个 SKAction.run 块的指令执行后运行下一个操作(如果它本身执行异步调用怎么办)?
额外问题:我在闭包捕获列表中将 self 设置为弱是否正确?因为我不希望在关闭游戏场景时将其保留为强有力的参考。
EDITED:好吧,类似的东西可以完成这项工作,但第二次淡入淡出在第一个淡入淡出结束之前开始......
private func runSampleSequence() {
// I want node1 to fadeIn
// then node2 to fadeIn
// then node1 to fadeOut
// then node2 to fadeOut
self.run(SKAction.sequence([
node1.fadeIn(withDuration: 1),
node2.fadeIn(withDuration: 2),
node1.fadeOut(withDuration: 4),
node2.fadeOut(withDuration: 3)
]))
}
通过从 SKNode 扩展返回操作:
extension SKNode {
func fadeIn(withDuration: TimeInterval) -> SKAction {
let action = SKAction.run {
self.run(SKAction.fadeIn(withDuration: withDuration))
}
return action
}
//TODO: Extend for each base SKAction ...
}