Daniel Mihaila
Daniel Mihaila

Reputation: 585

touchesBegan on local variable

I have a function that gets called repeatedly every 2 seconds, bringing a ball from the top of the screen with random texture each time. I want to be able to work with this ball in touchesBegan but I can't because it is a local variable. I've tried making it a global variable but this gave me an error saying i tried to add a skspritenode that already has a parent. any help would be appreciated. here's the code I used to bring down the balls.

override func didMoveToView(view: SKView) {

        var create = SKAction.runBlock({() in self.createTargets()})
        var wait = SKAction.waitForDuration(2)
        var waitAndCreateForever = SKAction.repeatActionForever(SKAction.sequence([create, wait]))
        self.runAction(waitAndCreateForever)
}

func createTargets() {

        let randomx = Int(arc4random_uniform(170) + 290)
        var ball = SKSpriteNode(imageNamed: "blueBlue")
        ball.zPosition = 0
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 11)
        ball.physicsBody?.dynamic = true
        ball.size = CGSize(width: ball.size.width / 1.5, height: ball.size.height / 1.5)
        let random = Int(arc4random_uniform(35))
        let textures = [texture1, texture2, texture3, texture4, texture5, texture6, texture7, texture8, texture9, texture10, texture11, texture12, texture13, texture14, texture15, texture16, texture17, texture18, texture19, texture20, texture21, texture22, texture23, texture24, texture25, texture1, texture7, texture18, texture24, texture25, texture1, texture7, texture18, texture24, texture25]
        ball.texture = textures[random]
        ball.position = CGPoint(x: randomx, y: 1400)
        addChild(ball)

}

Upvotes: 0

Views: 114

Answers (1)

Mundi
Mundi

Reputation: 80265

Local variable (in the function) is too little. (The variable gets destroyed as soon as you exit createTargets.

A global variable is presumably too much. Apparently, you are trying to create it upfront.

--> Use a class instance variable.

Besides, in touchesBegan you can check for the node being touched and - depending on what you intend to do - might be able to do without any variable.

Upvotes: 1

Related Questions