touchesMoved 当两个节点跨越 swift

touchesMoved when two nodes across swift

我在移动一些节点时遇到了问题,但我(终于)找到了一种方法,但后来我遇到了一个问题:当两个节点接触时,触摸将从一个节点移动到另一个节点!但我想要的是当我触摸一个节点时我会移动它直到我的手指离开屏幕 这是我的代码:

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

您需要跟踪 SKNodetouchesBegan

中触摸的手指

首先要记住的是,对于具有不同位置的 touchesMoved 中的每个手指,将返回相同的 UITouch 对象。所以我们可以使用 touchTracker 字典跟踪节点中的每个触摸。

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

也给每张卡片起个名字,这样我们就可以随时了解需要移动的节点。例如。

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

在touchesBegan中,我们将触摸下的节点添加到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
        }
    }
}

当触摸在 touchesMoved 中移动时,我们将从 touchTracker 取回节点并更新其位置。

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

    }
}

在touchesEnded中,我们再次更新最终位置,并从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)
    }
}