Search code examples
swiftsprite-kitspriteskspritenode

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😊

Below is the framework I've built up so far.

 import SpriteKit

var one = SKSpriteNode()

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")

        let one = SKSpriteNode(texture: oneTexture)

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

        self.addChild(one)


    }

    func removeOne() {

        one.removeFromParent()

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */

    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */

    }
}

Solution

  • 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
    
                self.addChild(one)
    
    
            }
    
            func removeOne() {
    
                one.removeFromParent()
    
            }
    }