Raul Gonzalez
Raul Gonzalez

Reputation: 875

SKSpriteNode drag movement by touch

I'm trying to drag a SKSpirteNode around the screen by touching the screen. But I want to be able to do a constant movement of the Sprite, currently my code only moves the sprite to the location of my touch but if I hold and move the sprite will not follow. Moreover I don't want to "have" to touch the SKSpriteNode to activate the movement, I want to touch anywhere on the screen and to have a movement response from that SKSpriteNode.

Here is my current code:

class GameScene: SKScene {
   override func didMoveToView(view: SKView) {
    // SpriteNode I want to drag around
    basket = SKSpriteNode(texture: basketTexture)
    self.addChild(basket)
   }

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */

    var nodeTouched = SKNode()
    var currentNodeTouched = SKNode()

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        nodeTouched = self.nodeAtPoint(location)
        basket.position = location

    }

Thank you any help appreciated.

Upvotes: 2

Views: 3283

Answers (1)

Raul Gonzalez
Raul Gonzalez

Reputation: 875

I solved this by using the func touchesMoved instead of touchesBegan and works perfectly and smoothly. here is the final code:

class GameScene: SKScene {
 override func didMoveToView(view: SKView) {
// SpriteNode I want to drag around
basket = SKSpriteNode(texture: basketTexture)
self.addChild(basket)
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */

var nodeTouched = SKNode()
var currentNodeTouched = SKNode()

for touch: AnyObject in touches {
    let location = touch.locationInNode(self)

    nodeTouched = self.nodeAtPoint(location)
    basket.position = location

}

Upvotes: 1

Related Questions