将发光效果添加到SKSpriteNode

Ore*_*ich 16 ios cifilter sprite-kit skeffectnode swift

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

   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)
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*tti 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])
    }
}
Run Code Online (Sandbox Code Playgroud)

现在给出一个SKSpriteNode

let sun = SKSpriteNode(imageNamed: "sun")
Run Code Online (Sandbox Code Playgroud)

所有你必须这样做

sun.addGlow()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 除了答案,这是一个了不起的答案.这是一项服务和洞察力的慷慨提供,以及在扩展方面思考的固有力量的另一个惊人演示.谢谢!!!这还不够.添加!!! ^ 3.一个性能查询:我已经修改了效果,最后手动将它们烘焙成纹理以用作精灵.这种模糊效果是否会更新每一帧.或者他们"烘焙"并简单地作为位图/精灵添加操作,除非底层对象(他们应用它们)发生变化? (4认同)
  • @ Knight0fDragon:您可以使用`fileprivate'限制扩展名对文件所在文件的可见性 (4认同)
  • @DaveKliman:您可以为effectNode的effectNode.name =“ GlowEffect”分配一个名称。稍后,您可以检索它并使其隐藏`childNode(withName:“ GlowEffect”)?. isHidden = true` (2认同)

小智 5

除此之外,您可以在任何类型的 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))
    }
}
Run Code Online (Sandbox Code Playgroud)