In swift how do I change the color of a SKSpriteNode? In swift how do I change the color of a SKSpriteNode? xcode xcode

In swift how do I change the color of a SKSpriteNode?


You can use the color property on SKSpriteNode, for example:

sprite.color = .whiteColor()

Bear in mind, if your SKSpriteNode has a texture you'll need to set the colorBlendFactor to a non-zero value to see your color. From the SKSpriteNode documentation on colorBlendFactor:

The value must be a number between 0.0 and 1.0, inclusive. The default value (0.0) indicates the color property is ignored and that the texture’s values should be used unmodified. For values greater than 0.0, the texture is blended with the color before being drawn to the scene.


If you want to animate the color change you can use an SKAction:

let colorize = SKAction.colorizeWithColor(.whiteColor(), colorBlendFactor: 1, duration: 5)sprite.runAction(colorize)

From the SKAction documentation on colorizeWithColor:colorBlendFactor:duration:

This action can only be executed by an SKSpriteNode object. When the action executes, the sprite’s color and colorBlendFactor properties are animated to their new values.


Copying an answer found on another forum:

The black parts of your image won't be blended, I can't see what the alpha is from your image, but if your image was just a black outline with a solid white center, if you blend, you'll see the color. If you want just the outline to blend, you need to create a white outline. With blending, you can set color to blend to black, but you can't blend to white.

link: https://www.reddit.com/r/swift/comments/30hr88/colorizing_a_skspritenode_doesnt_seems_to_work_as/