Reputation: 613
I want to move an SKSpriteNode over the screen with touch. The issue I have is that if I lock onto one sprite and then my finger drags it over another sprite the first one is let go and my finger starts to drag the second one. But once I touch the first sprite this is the only one I want to move. There must be a simple way to resolve this?
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
}
Upvotes: 0
Views: 627
Reputation: 613
Thanks to TheCodeComposer, I found the solution:
var targetNode: SKNode!
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)
targetNode = self.nodeAtPoint(touchLocation)
objectTouched(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
}
}
I only define
targetNode
once and then continue to use it instead of redefining it in touchesMoved:
Upvotes: 1
Reputation: 711
This is happening because your touchesMoved function is running every time your finger moves and if your finger moves over a new node, that node will be assigned to targetNode. You can fix this by changing this line:
let targetNode = self.nodeAtPoint(touchLocation)
To this:
let targetNode = self.nodeAtPoint(touch)
This way the node at the first touch will be the one that follows your finger and not the one at the last touch.
Upvotes: 1