touchesMoved当两个节点跨越swift时

时间:2015-02-25 09:06:46

标签: ios swift sprite-kit

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

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

1 个答案:

答案 0 :(得分:2)

您需要跟踪SKNode

中触及的touchesBegan手指

要记住的第一件事是在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)
    }
}