Gusfat
Gusfat

Reputation: 111

SKScene + TouchBegan Bug

I have my SKScene with 1 empty node (buttonsGroup). In my GameView class i create a node (ball1) that its parent of the empty node.

    buttonsGroup = childNodeWithName("ball1")


    var ball1 = SKSpriteNode(imageNamed: "ball")
    ball1.name == "ball1"
    buttonsGroup.addChild(ball1)

My problem comes when i try to move the node using TouchesBegan:

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

    for touch in (touches as! Set<UITouch>) {

        let location = touch.locationInNode(self)
        let touchNode = nodeAtPoint(location)

        if touchNode.name != "ground" {
            touchNode.position = location
        }
    }
} 

I already know that if you use SKScene and the touchNode location they'll return different values (or at least it appears so). In this case the Node just jump to nowhere. The size of my SKScene is 480x320.

Does anyone knows a solution? If i do by hand (without SKScene) it works without any problem. I already had this problem multiple times while trying to use moveBy action or any other action that requires my position in the view.

Upvotes: 0

Views: 83

Answers (1)

0x141E
0x141E

Reputation: 12753

If you are trying to move the ball, you will need to convert the touch location from scene coordinates to the ball's parent's coordinates with convertPoint:toNode or convertPoint:fromNode.

For example,

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        let node = nodeAtPoint(location)
        if (node.name != "ground") {
            let locationInNode = convertPoint(location, toNode:node.parent!)
            node.position = locationInNode
        }
    }
}

Upvotes: 1

Related Questions