swift - 如何使用 Swift 更改 SpriteKit 中具有特定名称的所有节点的颜色

标签 swift sprite-kit

我正在尝试更改 SpriteKit 中节点的每个实例的颜色。当我尝试将其放入更新方法时,它只更改了一个而不是全部。

override func update(currentTime: CFTimeInterval) {
    if changeColor {
        self.enumerateChildNodesWithName("blocks", usingBlock: { node, stop in
            block?.color = UIColor.orangeColor()
        })
    }
}

最佳答案

我认为您应该更改节点 的颜色,而不是某些 block 变量的颜色。您将检索所有具有该名称的 SKNode。但是那些节点没有颜色属性。只有一些子类,例如 SKSpriteNode 具有 color 属性。因此,您必须添加一些额外的逻辑来更改颜色。例如,您可以尝试将 node 转换为 SKSpriteNode,然后才更改 color:

self.enumerateChildNodesWithName("blocks", usingBlock: { node, stop in
    if let sprite = node as? SKSpriteNode {
        sprite.color = UIColor.orangeColor()
    }
})

正如@appzYourLife 正确提到的那样,代码可以简化/快速化为

self.enumerateChildNodesWithName("blocks") { node, stop in
    if let sprite = node as? SKSpriteNode {
        sprite.color = .orangeColor()
    }
}

关于swift - 如何使用 Swift 更改 SpriteKit 中具有特定名称的所有节点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699122/

相关文章:

ios - swift 错误 : Cannot call value of non-function type "SKSpriteNode"

ios - CoreData 中的异步读取 - 使用 newBackgroundContext + FetchRequest 与 newBackgroundContext + NSAsynchronousFetchRequest 的区别?

swift - Grand Central Dispatches - 执行乱序?

swift - 自定义 MKAnnotationView 想要再次被点击

ios - Swift:无法分配给表达式的结果

swift - 动画后如何去除SKTexure

ios - Swift - 实例化新 View Controller 时如何保留对旧 View Controller 的引用?

macos - Spritekit OS X 如何使用自定义字体

ios - SpriteKit 内存泄漏?

ios - 使用 swift (SpriteKit) 检测触摸压力(力)