keloa
keloa

Reputation: 115

touchesMoved when two nodes across swift

I had a problem with movning some nodes around but I found a way (finally) but then I faced a problem which is : when two nodes gets across the touch will move from one node to the other ! but what I want is when I touch a node I will move it until I move my finger from the screen here is my code :

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        var location = touch.locationInNode(self)
        let node = nodeAtPoint(location)
        if node == firstCard{
            firstCard.position = location
        }else if node == secondCard{
            secondCard.position = location
            println("Second Card Location")
            println(secondCard.position)
        }else{
            println("Test")
        }
                        }
        }

Upvotes: 1

Views: 1689

Answers (1)

rakeshbs
rakeshbs

Reputation: 24572

You need to keep track of the SKNode the finger touched in touchesBegan

First thing to remember is the the same UITouch object is returned for each finger in touchesMoved with different locations. So we can keep track of the each touch in the node using a touchTracker dictionary.

var touchTracker : [UITouch : SKNode] = [:]

Also give a name to each card, so that we can keep track of the nodes that need to be moved. For example.

card1.name = "card"
card2.name = "card"

In touchesBegan, we will add the node that is under the touch to the touchTracker.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = self.nodeAtPoint(location)
        if (node.name == "card") {
            touchTracker[touch as UITouch] = node
        }
    }
}

When a touch is moved inside touchesMoved, we will get the node back from the touchTracker and update its position.

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    for touch in touches {
        let location = touch.locationInNode(self)
        let node = touchTracker[touch as UITouch]
        node?.position = location

    }
}

In touchesEnded, we update the final position again, and remove the touch key-value pair from touchTracker.

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = touchTracker[touch as UITouch]
        node?.position = location
        touchTracker.removeValueForKey(touch as UITouch)
    }
}

Upvotes: 2

Related Questions