将发光效果添加到SKSpriteNode

时间:2016-11-01 14:33:06

标签: ios swift sprite-kit cifilter skeffectnode

我在黑暗的屏幕上有一个移动的黑色图像,以便更容易看到我想为图像添加白色光晕。这是我的动态图像代码:

   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)

如果您需要更多信息,我不知道如何或者使用什么来添加发光,请询问。

2 个答案:

答案 0 :(得分:29)

我创建了此扩展程序,以向SKSpriteNode

添加发光效果

只需将其添加到您的项目

即可
extension SKSpriteNode {

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

现在给出一个SKSpriteNode

let sun = SKSpriteNode(imageNamed: "sun")

所有你必须这样做

sun.addGlow()

enter image description here

答案 1 :(得分:3)

只是添加到此,您可以在任何类型的SKNode上执行此操作,方法是首先使用SKView实例上可用的纹理(来自:SKNode)方法呈现其内容。

示例:

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))
    }
}