Having a glow behind a sprite can give game a move lively environment. In this blog post I am going to present a way of adding a glow to SKSpriteNode using an instance of SKEffectNode.
Node Tree
First of all let’s take a look on the node tree needed for achieving the end result.
SKSpriteNode (root)
Displays a texture what needs a glow.
SKNode
Enables running actions on the glow without causing to render the glow again. Running an action on the SKEffectNode would cause it to redraw although it is rasterizing its content. Also note that the zPosition of the node should be -1 as the glow should be rendered behind the root node.
SKEffectNode
Applies gaussian blur filter to the child node what in this case is a SKSpriteNode displaying the same texture as the root node. It is important to cache the content by setting shouldRasterize to true. Otherwise the glow gets re-rendered in every frame and therefore uses computing power unnecessary.
SKSpriteNode
Uses the same texture as the root node what is rendered together with the filter SKEffectNode provides.
SKSpriteNode Extension
import SpriteKit | |
extension SKSpriteNode { | |
/// Initializes a textured sprite with a glow using an existing texture object. | |
convenience init(texture: SKTexture, glowRadius: CGFloat) { | |
self.init(texture: texture, color: .clear, size: texture.size()) | |
let glow: SKEffectNode = { | |
let glow = SKEffectNode() | |
glow.addChild(SKSpriteNode(texture: texture)) | |
glow.filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius": glowRadius]) | |
glow.shouldRasterize = true | |
return glow | |
}() | |
let glowRoot: SKNode = { | |
let node = SKNode() | |
node.name = "Glow" | |
node.zPosition = -1 | |
return node | |
}() | |
glowRoot.addChild(glow) | |
addChild(glowRoot) | |
} | |
} |
Download Playground
Please check out the playground demonstrating rendering the glow in code: GlowingSprite (GitHub)
One reply on “Adding an animating glow to SKSpriteNode”
[…] Adding an animating glow to SKSpriteNode (January 17, 2018) […]
LikeLike