sprite-kituikitsksceneskemitternode

Stop SKEmitterNode to emit particles


I have a SKEmitterNode and I'm trying to stop it when a button is pressed. I add my node in this way:

let followLine = SKAction.followPath(border.CGPath, asOffset: false, orientToPath: true, duration: 2.0)
let loopAction = SKAction.repeatActionForever(followLine)
emitterNode.targetNode = scene
emitterNode.runAction(loopAction, withKey: "loop")
addChild(emitterNode)

I add the emitterNode to my SKScene and when I want to stop the particles I tried all these possible ways:

let action = SKAction.runBlock { [weak self] in
    self?.emitterNode.particleBirthRate = 0
}
emitterNode.runAction(action)


emitterNode.removeAllActions()
emitterNode.removeFromParent()


removeAllActions()


let remove = SKAction.removeFromParent()
emitterNode.removeActionForKey("loop")
emitterNode.runAction(remove)

The emitter doesn't stop and the animation continues.


Solution

  • I figured out it was an issue with my code. I was trying to stop an emitter node which was created in a computer property and so was allocated very time it was accessed. The instance wasn't obviously the same and the emitter node wasn't stopping. This is my tip. Don't confuse the syntax for computer properties with the syntax to initialize a property with a closure. These two pieces of code are very different:

    // Created only once
    var laserButton: ParticlesLoadingButton = {
        let button = ParticlesLoadingButton(frame: CGRect(x: 100, y: 100, width: 200, height: 100))
        button.particleEffect = .Laser
        button.particleColor = UIColor.orangeColor()
        return button
    }()
    
    // Created every time it is accessed
    var laserButton2: ParticlesLoadingButton {
        let button = ParticlesLoadingButton(frame: CGRect(x: 100, y: 100, width: 200, height: 100))
        button.particleEffect = .Laser
        return button
    }