NickvR NickvR - 2 years ago 70
Swift Question

Add SpriteNodes and Remove Based on Time or click using SpriteKit

I am new to swift and looking to build my first basic game. The game I have in mind involves sprites generating at random and then disappearing based on time or a click if the click is within the time allocated. So far I have created the basic framework and am still messing around with design. My problem comes in where I can't seem to remove the sprite based on time (its generating fine). Any help is appreciated and thanks in advance

Answer Source

It doesn't disappear because your create a new SpiteNode, but try to remove the old one, do it like this:

    var one : SKSpriteNode! //instead of creating it without data, just define the type(not necessary, but I would do it)

    class GameScene: SKScene {
        override func didMoveToView(view: SKView) {
            /* Setup your scene here */

            let myFunction = SKAction.runBlock({()in self.addOne()})
            let wait = SKAction.waitForDuration(5)
            let remove = SKAction.runBlock({() in self.removeOne()})

            self.runAction(SKAction.sequence([myFunction, wait, remove]))


        func addOne() {

            let oneTexture = SKTexture(imageNamed: "blue button 10.png")

            one = SKSpriteNode(texture: oneTexture) //removed the let, so you dont create a new "one"

            one.position = CGPoint(x: CGRectGetMidX(self.frame) - 100, y: CGRectGetMidY(self.frame) + 250)
            one.zPosition = 1



        func removeOne() {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download