Search code examples
swifttimersprite-kitsknode

setup timer for a node


im trying to set a timer for every node that create (by touching the screen). I want to set up a timer to know when to remove the node (by using removefromparent). I want that if some node is in locate in some position for 5 second then it remove from the screen. im new for swift and I don't really get how should I set the timer. I use this init:

let ballTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: <#T##(Timer) -> Void#>)

I understood that the "withTimeInterval" is for setting the second - so I set it to 1. the "repeats" and the "block" properties I don't really get and so im not sure if im using the right function.

can anyone help me with that?


Solution

  • You should use the update() function of your scene. That override runs every frame so you can check your positioning then, and keeping track of each node, you can start or restart a wait() action that removes the node on completion.

    Something like,

    if ball.position.x == 200 && ball.position.y == 200 {
        let wait = SKAction.wait(forDuration: 5.0)
        let remove = SKAction.removeFromParent()
        let sequence = SKAction.sequence([wait, remove])
    
        ball.run(sequence)
    }else{
        ball.removeAllActions()
    }
    

    Note: you should not use specific coordinates like that though, use a range of at least a few points or round up the x and y values.