Search code examples
swiftxcodesprite-kituikitdraggable

drag a SKSprite Node or a UIImage by my finger more accurately, maintain offset?


I am trying to drag a SKSprite Node or a UIImage by my finger more accurately. For example if a touch is registered in the bottom corner of the node and moved, I want to the image to maintain the distance between your finger location and the center of node. Currently the center location jumps to the finger location.

Here is my code, it seems the offset code (touchl - previousLocation) isn't being maintained. Any suggestions?

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let touchl = touch.location(in: self)
            let previousLocation = touch.previousLocation(in: self)
                       triangle.position.x = touchl.x + (touchl.x - previousLocation.x)
                       triangle.position.y = touchl.y + (touchl.y - previousLocation.y)
                       }
            }

Solution

  • override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let touchl = touch.location(in: self)
            let previousLocation = touch.previousLocation(in: self)
            let dx = touchl.x - previousLocation.x
            let dy = touchl.y - previousLocation.y
            
                triangle.position.x = triangle.position.x + dx
                triangle.position.y = triangle.position.y + dy
            }
           }