Search code examples
xcodeswifttouchesmoved

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


           }
          }
         }

Solution

  • Declare an optional SKNode to hold the current rotating node like var rotatingNode:SKNode?. You can override touchesBegan.

    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" || node.name == "rightCircle" {
    
                self.rotatingNode = node
    
    
               }
              }
             }
    

    From your comment it seems like you have other code in touchesMoved than what is posted in your question. But if you want to rotate either circle or rightCircle then say something like:

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        for touch in touches {
    
    
    
    
                let dy = self.rotatingNode?.position.y - location.y
                let dx = self.rotatingNode?.position.x - location.x
                let angle2 = atan2(dy, dx)
                self.rotatingNode?.zRotation = angle2
    
    
    
              }
             }
    

    Then in touchesEnded:

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