Search code examples
iosswiftsprite-kitdragskshapenode

Dragging of SKShapeNode Not Smooth


So I am super new to swift and iOS development but not totally new to programming, and was just going through some tutorials, but basically my code looks like this:

import SpriteKit


class GameScene: SKScene {


override func didMoveToView(view: SKView) {
    let circle = SKShapeNode(circleOfRadius: 30.0)
    circle.position = CGPointMake(100, 200)
    addChild(circle)
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        touchedNode.position = location;
    }
}

}

When I build this it recognizes and moves the circle when I drag it, but only for about 30 pixels and then I have to touch it again to move it. What am I doing wrong here?


Solution

  • Tokuriku, thanks so much, you we're not quite right but it got me to the eventual answer, here it is

    import SpriteKit
    
    class GameScene: SKScene {
    var circleTouch: UITouch?
    
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        let circle = SKShapeNode(circleOfRadius: 40.0)
        circle.fillColor = UIColor.blackColor()
        circle.position = CGPoint(x: size.width * 0.5, y: size.height * 0.2)
        circle.name = "userCircle"
        addChild(circle)
    }
    
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        for touch in touches {
            if nodeAtPoint(touch.locationInNode(self)).name == "userCircle" {
                circleTouch = touch as? UITouch
            }
        }
    }
    
    override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
        for touch in touches {
            if circleTouch != nil {
                if touch as UITouch == circleTouch! {
                    let location = touch.locationInNode(self)
                    let touchedNode = nodeAtPoint(location)
                    touchedNode.position = location
                }
            }
        }
    }
    
    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        for touch in touches {
            if circleTouch != nil {
                if touch as UITouch == circleTouch! {
                    circleTouch = nil
                }
            }
        }
    }