为 SKSpriteNode 添加发光效果

Add glowing effect to an SKSpriteNode

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

   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)

我不确定如何或使用什么来添加光晕,如果您需要更多信息,请询问。

我创建这个扩展是为了给 SKSpriteNode 添加发光效果

只需将其添加到您的项目中

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

现在给定一个 SKSpriteNode

let sun = SKSpriteNode(imageNamed: "sun")

你所要做的一切

sun.addGlow()

除此之外,您可以在任何类型的 SKNode 上执行此操作,方法是首先使用 SKView 实例上可用的 texture(from: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))
    }
}