Reputation: 449
I have an SKSpriteNode
that I want to drag around the screen via touchesMoved
. However, I do not want the sprite to move if the touch didn't originate on the location of the sprite in the first place (no skipping around the scene).
I have a intermittent solution but believe something is both more elegant and more functional as this solution doesn't work correctly - it appears as if the sprite location doesn't keep up with the touch location if the user drags the sprite very fast.
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
var touchPoint : CGPoint = location
var muncherRect = muncherMan.frame
if (CGRectContainsPoint(muncherRect, touchPoint)) {
muncherMan.position = location
} else {
}
}
}
Upvotes: 0
Views: 143
Reputation: 4413
You can implement these three methods to achieve what you want: touchesBegan
, touchesMoved
and touchesEnded
. When you touched muncherMan
, set muncherManTouched
true which indicated muncherMan
would probably be moved in the next frame. When finishing the move or touch, set muncherManTouched
false and wait for the next touch.
Here's the example code. I add a name for muncherMan
so we can determine which node is being touched in touchesBegan
.
var muncherManTouched = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
...
muncherMan.name = "muncherMan"
self.addChild(muncherMan)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let nodeTouched = self.nodeAtPoint(location)
if (nodeTouched.name == "muncherMan") {
muncherManTouched = true
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if (muncherManTouched == true) {
muncherMan.position = location
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
muncherManTouched = false
}
Upvotes: 2