coding22 coding22 - 7 months ago 11
Swift Question

How do I get my node to rotate even if my finger is outside the node?

Ill try to explain this the best way I can. I have this circle that I can rotate when my finger is moving on the circle. The problem Im having is that when Im rotating the circle and I move my finger outside the circle the rotation stops. I would like it to still have the touch even if my finger is outside the node. It works when Im in a single view controller but in spritekit I cant figure it out.

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

for touch in touches {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)


if node.name == "circle" {

let dy = circle.position.y - location.y
let dx = circle.position.x - location.x
let angle2 = atan2(dy, dx)
circle.zRotation = angle2


}
}
}

Answer

If your view is not very complicated, you can override touchesBegan and set a flag.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = self.nodeAtPoint(location)


        if node.name == "circle" {

            self.isTouchInCircle = true


           }
          }
         }

change touchesMoved to:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch in touches {


        if  self.isTouchInCircle {

            let dy = circle.position.y - location.y
            let dx = circle.position.x - location.x
            let angle2 = atan2(dy, dx)
            circle.zRotation = angle2


           }
          }
         }

Then in touchesEnded:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.isTouchInCircle = false
    }