SKSpriteNode drag movement by touch

2019-05-26 13:11发布

问题:

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.

回答1:

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

}