Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show shadow or any glow effect for SKSpriteNode when it moved on screen only?

I want to show any effects or animations for my SKSpriteNode when it was dragging on screen.

I gone through many sites but i didn't find relevant answer for my question.I have little bit knowledge on SKSpriteNode.

Can any one guide me to solve this issue.

Thanks.

like image 314
Mounika Avatar asked Dec 04 '25 16:12

Mounika


1 Answers

Use a factory to make a shadow:

import SpriteKit

class MAKE {

    private static let view:SKView = SKView()

    static func makeShadow(from source: SKTexture, rgb: SKColor, a: CGFloat) -> SKSpriteNode {
        let shadowNode = SKSpriteNode(texture: source)
            shadowNode.colorBlendFactor = 0.5  // makes the following line more effective
            shadowNode.color = SKColor.gray // makes for a darker shadow. Off for "glow" shadow
        let textureSize = source.size()
        let doubleTextureSize = CGSize(width: textureSize.width * 2, height: textureSize.height * 2)
        let framer = SKSpriteNode(color: UIColor.clear, size: doubleTextureSize)
            framer.addChild(shadowNode)
        let filter = CIFilter(name: "CIGaussianBlur")
        let blurAmount = 10
        filter?.setValue(blurAmount, forKey: kCIInputRadiusKey)
        let effectsNode = SKEffectNode()
            effectsNode.filter = filter
            effectsNode.blendMode = .alpha
            effectsNode.addChild(framer)
            effectsNode.shouldRasterize = true
        let tex = view.texture(from: effectsNode)
        let shadow = SKSpriteNode(texture: tex)
            shadow.colorBlendFactor = 0.5
            shadow.color = rgb
            shadow.alpha = a
            shadow.zPosition = -1
    return shadow
    }
}

Now make a button anyway you like, but make sure you have created a buttonTexture that's the exact same size and shape as your button, preferably a grey rendition of it. You'll need this to send to the blurring factory shadowmaker above, like this:

shadowSprite = MAKE.makeShadow(from: buttonTexture, rgb: myColor, a: 0.33)
        shadowSprite.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 5)
        addChild(shadowSprite)

You can see more details on how and why a factory, here: Create \(Use) SKView as \(in a) factory \(static class)

like image 101
Confused Avatar answered Dec 06 '25 11:12

Confused



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!