coding22 coding22 - 7 months ago 18
Swift Question

Why does my node stop rotating if I move my finger off my node and into the GameView?

I have this node I can rotate if my finger is on it. The problem Im having is that when Im rotating the node and my finger slides off the node and onto the view it stops rotating. How would I still be able to have that touch if my finger isn't on the node anymore?

For example I have a UISlider in my app and if I have my finger on my slider and I move down and then try to move the slider to the left and right it still works. How would I be able to do the same for my node where the touch event is still there? Let me know if you don`t get what I'm saying. Here is the code I'm using to rotate my node:

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"
//lets user rotate when there is one finger on node.
let dy = circle.position.y - location.y
let dx = circle.position.x - location.x
let angle2 = atan2(dy, dx)
circle.zRotation = angle2
}

Answer

You should store the last node in a instance var and then using that try to keep rotating even if it didnt touch it.

class MyClass  {
var lastNodeSelected:SKNode?

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

    if node.name == "circle"                 
       lastNodeSelected = node
    }
}


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

    if lastNodeSelected != nil {
       let touchedNode = lastNodeSelected!                 
       let dy = touchedNode.position.y - location.y
       let dx = touchedNode.position.x - location.x
       let angle2 = atan2(dy, dx)
       touchedNode.zRotation =  angle2
    }

override func touchesEnd(touches: Set<UITouch>, withEvent event: UIEvent?) {
   lastNodeSelected = nil