Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add glowing effect to an SKSpriteNode

I have a moving black image on a dark screen, to make it easier to see I would like to add in a white glow to the image. This is my code for the moving image:

   Ghost = SKSpriteNode(imageNamed: "Ghost1")
Ghost.size = CGSize(width: 50, height: 50)
Ghost.position = CGPoint(x: self.frame.width / 2 - Ghost.frame.width, y: self.frame.height / 2)

Ghost.physicsBody = SKPhysicsBody(circleOfRadius: Ghost.frame.height / 1.4)
Ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost
Ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall
Ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall | PhysicsCatagory.Score
Ghost.physicsBody?.affectedByGravity = false
Ghost.physicsBody?.isDynamic = true
Ghost.zPosition = 2

self.addChild(Ghost)

I'm not sure how or what to use to add in a glow, if you need more information please ask.

like image 675
Oren Edrich Avatar asked Nov 01 '16 14:11

Oren Edrich


2 Answers

I created this extension to add a glow effect to an SKSpriteNode

Just add this to your project

extension SKSpriteNode {

    func addGlow(radius: Float = 30) {
        let effectNode = SKEffectNode()
        effectNode.shouldRasterize = true
        addChild(effectNode)
        let effect = SKSpriteNode(texture: texture)
        effect.color = self.color
        effect.colorBlendFactor = 1
        effectNode.addChild(effect)
        effectNode.filter = CIFilter(name: "CIGaussianBlur", parameters: ["inputRadius":radius])
    }
}

Now given an SKSpriteNode

let sun = SKSpriteNode(imageNamed: "sun")

all you have to do it

sun.addGlow()

enter image description here

like image 178
Luca Angeletti Avatar answered Oct 18 '22 20:10

Luca Angeletti


Just to add to this, you can perform this on any type of SKNode by first rendering its contents using the texture(from:SKNode) method available on an SKView instance.

Example:

extension SKNode
{
    func addGlow(radius:CGFloat=30)
    {
        let view = SKView()
        let effectNode = SKEffectNode()
        let texture = view.texture(from: self)
        effectNode.shouldRasterize = true
        effectNode.filter = CIFilter(name: "CIGaussianBlur",withInputParameters: ["inputRadius":radius])
        addChild(effectNode)
        effectNode.addChild(SKSpriteNode(texture: texture))
    }
}
like image 5
prolific8 Avatar answered Oct 18 '22 20:10

prolific8