在屏幕上移动SKSpriteNode

时间:2015-09-20 14:41:25

标签: swift touch skspritenode touchesbegan touchesmoved

我想通过触摸在屏幕上移动SKSpriteNode。我遇到的问题是,如果我锁定一个精灵然后我的手指将它拖到另一个精灵上,那么第一个精灵就会松开,我的手指开始拖动第二个精灵。但是一旦我触摸了第一个精灵,这是我唯一想要移动的精灵。 必须有一个简单的方法来解决这个问题?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */
    let touch: UITouch = touches.first as UITouch!
    touchLocation = touch.locationInNode(self)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let touch: UITouch = touches.first as UITouch!
    let newTouchLocation = touch.locationInNode(self)
    let targetNode = self.nodeAtPoint(touchLocation)
    if targetNode.physicsBody!.categoryBitMask != PhysicsCategory.Ball {
    targetNode.runAction(SKAction.moveBy(CGVector(point: newTouchLocation - touchLocation), duration: 0.0))
    touchLocation = newTouchLocation
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    //I don't do anything with this yet
}

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为每次手指移动时都会运行touchesMoved函数,如果手指在新节点上移动,该节点将被分配给targetNode。您可以通过更改此行来解决此问题:

let targetNode = self.nodeAtPoint(touchLocation)

对此:

let targetNode = self.nodeAtPoint(touch)

这样,第一次触摸的节点将是跟随手指的节点,而不是最后一次触摸的节点。