Search code examples
swiftsprite-kitsequencessknodeparticles

How to add and remove a SKErmitterNode within a sequence?


I'm adding a SKErmitterNode from the update() function. I want to remove the SKErmitterNode after 2 seconds, therefore I made a sequence but in the sequence, I can´t add Nodes. And if I add the Node outside of the sequence it gets added over and over again(because I´m doing all of this in the update function) Does someone know a better way to do this?

Here is my Code from the update function:

 override func update(_ currentTime: CFTimeInterval) {

    if player.position.y <= player.size.height / 2{

        self.player.removeFromParent()

        if let particles = SKEmitterNode(fileNamed: "MyParticle.sks") {
            particles.position = player.position

            let addParticle = addChild(particles)
            let wait = SKAction.wait(forDuration: 2.0)
            let removeParticle = SKAction.removeFromParent()
            let particleSequence = SKAction.sequence([addParticle, wait, removeParticle]) //Error ->Cannot convert value of type 'Void' to expected element type 'SKAction'
            self.run(SKAction.run(particleSequence))

        }
    }

Solution

  • So what I recommend for you to do is to create a function like the following

    func myExplosion (explosionPosition: CGPoint){
        let explosion = SKEmitterNode(fileNamed: "MyParticle")// borrowed this from you
        explosion?.position = explosionPosition
        explosion?.zPosition = 3
        self.addChild(explosion!)
        self.run(SKAction.wait(forDuration: 2)){//you can always change the duration to whatever you want
            explosion?.removeFromParent()
        }
    }
    

    then when it is time to use this function, use it like so

    myExplosion(explosionPosition: player.position)
    

    Hope this can help you out.