Home > OS >  SKSpriteNode spinning too quickly on rotation
SKSpriteNode spinning too quickly on rotation

Time:06-06

Currently I am trying to rotate a SKSpriteNode to 45 degrees when one side of the screen is touched, and -45 degrees when the other side is touched, and back to zero when the touch has ended. The problem is instead of going fluidly the fastest route from -45 to 0, or -45 to 45, it seems to spin the opposite direction very quickly multiple times until it reaches said degree. Here is my current code:

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
                let location = touch.previousLocation(in: self)
                let position = touch.location(in: self)
                let node = self.nodes(at: location).first


//IF LEFT SCREEN IS TOUCHED
if position.x < 0 {
    let rotate = CGFloat(45.0 * .pi / 180)
    let rotateAction =  SKAction.rotate(toAngle: rotate, duration: 0.2)
    car.run(rotateAction, withKey: "rotating")
         
    

//IF RIGHT SCREEN IS TOUCHED
            } else {
                let rotate2 = CGFloat(-45.0 * .pi / 180)
                let rotateAction2 =  SKAction.rotate(toAngle: rotate2, duration: 0.2)
                car.run(rotateAction2, withKey: "rotating")
                     
         
                }
            
        }
            
    }





 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

     car.removeAction(forKey: "rotating")
     
         let rotate4 = CGFloat(0.0 * .pi / 180)
         let rotateAction4 =  SKAction.rotate(toAngle: rotate4, duration: 0.2)
     car.run(rotateAction4, withKey: "rotating4")
         
        }

CodePudding user response:

Add a shortestUnitArc: true parameter:

let rotateAction = SKAction.rotate(toAngle: rotate, duration: 0.2, shortestUnitArc: true)

Note that there are many overloads of rotate:

  • Related