Marcelo
Marcelo

Reputation: 41

How do I call a touchesBegan function?

I simply want to make the position of "mainBall" the position of the touch. How can I call the touchesBegan function?, if i create a override function with touchesBegan outside of the "override function didMoveToView(view: SKView) then it cant access the "mainBall" "SKSpriteNode" and its location because it is inside didMoveToView. I am puzzled, any help is much appreciated in advanced.

import SpriteKit
import UIKit

let MainBallCategoryName = "mainBall"

class GameScene: SKScene {

override func didMoveToView(view: SKView) {
    super.didMoveToView(view)

    var mainBall = childNodeWithName(MainBallCategoryName) as SKSpriteNode

    println(mainBall.position)


func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        let location = touch.locationInNode(self)
        mainBall.position = location


      }
    }
  }
}

Upvotes: 0

Views: 1878

Answers (1)

Christian
Christian

Reputation: 22343

You don't need to call the touchesBegan-method by yourself. That does Swift for you. Also you have to move the method outside of your didMoveToView method. You can't nest a function inside another function:

So you have to do something like that:

let MainBallCategoryName = "mainBall"

class GameScene: SKScene {
    //Make your ball to a global variable to access it in your 'touchesBegan' method
    var mainBall:SKSpriteNode!

    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)

        var circle = SKShapeNode(circleOfRadius: 10)

        mainBall = SKSpriteNode()
        mainBall.name = MainBallCategoryName
        mainBall.addChild(circle)

        println(mainBall.position)

    }

    //Add the 'override' to your method
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch in touches {
            let location = touch.locationInNode(self)
            mainBall.position = location


        }
    }
}

As you see, I've added the override to your touchesBegan method. That's important because that way Swift knows "Oh he want to handle a touch by himself". Also I've moved the mainBall variable outside of your didMoveToView method. Because that way you can access it in your touchesBegan method.

Upvotes: 1

Related Questions