Search code examples
iosswifttouchesmoved

How do I make an if statement for my rotating circle in Swift?


I have this circle and it can rotate 360 degrees to the left and right when the user has their finger on the node and is rotating. I need to figure out how to make an if statement so when it rotates to the left I can add an action and when it rotates to the right I can add another action. Here is the code I have:

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 == "rotatecircle" {


            //lets user rotate circle like a knob 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

        } 
         } 
          }

Solution

  • One approach would be to compare the angle2 value to the angle value from the previous touch. You can then create an if statement that does what you want based on the direction of the rotation.

    Some pseudo-code:

    In your class:

    var previousAngle:Double
    

    In touchesMoved

    let delta = (angle2 - previousAngle) mod M_PI
    if delta > 0 {
        // do action 1
    }
    else {
        // do action 2
    }
    previousAngle = angle2
    

    You will need some logic to check if this is the first touch. In that case you don't have a previousAngle yet, so you don't want to take an action.