How do you change the color of all of the nodes of a specific name in SpriteKit with Swift

有些话、适合烂在心里 提交于 2019-12-08 07:34:14

问题


I'm trying to change the color of every single instance of a node in SpriteKit. When I try to put it in the update method, it only changes one and not all of them.

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

回答1:


I think you should change the color of the node, not of some block variable. You will retrieve all SKNodes with that name. But those nodes don't have a color property. Only some subclasses, for example the SKSpriteNode have a color property. You therefore have to add some additional logic to change the color. For example you could try to convert the node to SKSpriteNode and only then change the color:

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

As @appzYourLife correctly mentioned that code can be simplified / swiftyfied to

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


来源:https://stackoverflow.com/questions/34699122/how-do-you-change-the-color-of-all-of-the-nodes-of-a-specific-name-in-spritekit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!