Anders Anders - 4 months ago 11
Swift Question

How to remove SKSpriteNodes after specific amount of time

I want to add SKSpriteNodes and place them randomly in the scene with specific time interval. Then I want these nodes to be removed after a specific time.

The problem is that the removal does not work.

I try to use removeFromParent() in a SKAction.sequence but the code is not executed.

How can I remove SKSpriteNodes after specific amount of time?

import SpriteKit

class GameScene: SKScene {

override func didMoveToView(view: SKView) {
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(placeFruit),
SKAction.waitForDuration(1.0)
])))
}

func placeFruit() {

let fruit = SKSpriteNode(imageNamed: "apple")
fruit.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height * random(min: 0, max: 1))

addChild(fruit)

runAction(
SKAction.sequence([
SKAction.waitForDuration(1.0),
SKAction.removeFromParent()
]))
}

override func update(currentTime: CFTimeInterval) {
}

func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(#min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}

}

Answer

You are running your sequence action on self instead of your fruit node.

Simply change your function like so :

func placeFruit() {

    let fruit = SKSpriteNode(imageNamed: "apple")
    fruit.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height * random(min: 0, max: 1))

    addChild(fruit)

    fruit.runAction(
        SKAction.sequence([
            SKAction.waitForDuration(1.0),
            SKAction.removeFromParent()
        ])
    )

}