Search code examples
swiftxcodearkitparticle-systemscnnode

SCNParticleSystem not adding to SCNNode on touchesbegan


I am placing multiple SCNNodes in my view on load of my application. On touchesbegan I am removing whatever node is tapped on.

All of this works so far so I know my code is working however just adding a SCNParticleSystem is giving me issues.

I have put two stars (**) by the lines that are not working

 // On tap
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Register tap
    let touch = touches.first!
    // Get location
    let location = touch.location(in: sceneView)
    // Create a hit
    let hitList = sceneView.hitTest(location, options: nil)

    if let hitObject = hitList.first {
        // Get node from hit
        let node = hitObject.node
        if node.name == target {
            score += 3
            playAudio(fileName: "two")
            **let explosion = SCNParticleSystem(named: "stars.scnp", inDirectory: nil)
            **node.addParticleSystem(explosion!)
            node.removeFromParentNode()
            // Async call
            DispatchQueue.main.async {
                node.removeFromParentNode()
                self.scoreLabel.text = String(self.score)
            }
        }
    }
}

How do I attach the particle to the node?


Solution

  • If you want to see the explosion and remove the node, just set a wait timer, for example:

    let explosion = SCNParticleSystem(named: "stars.scnp", inDirectory: nil)
    node.addParticleSystem(explosion!)
    
    let waitAction = SCNAction.wait(duration: 3)
    node.runAction(waitAction, completionHandler: {
        self.node.removeFromParentNode()
        self.scoreLabel.text = String(self.score)
    })
    

    You can post the wait action on any node, so if you have a central node in the scene, it will work with that as well