简体   繁体   中英

SKSpriteNode get the value of the angle from 0 to 360 degrees

I rotate the SKSpriteNode. I need to get the value of the angle in degrees. I use SKNode zRotation :

print((childNode(withName: "wheel")?.zRotation)! * 180 / CGFloat.pi)

The documentation says:

A positive value indicates a counterclockwise rotation.

But with the rotation of the wheel, angles are printed only up to 180 degrees. Then prints negative angles from -180 to 0! Why? How do I get the angles from 0 to 360 degrees?

My recommendation is that you should not do what you're suggesting. If the rotation is coming out negative, it's because it is negative. However, you can do this if you really want to: If the result is negative, add 360 to it. We can readily write a CGFloat extension to take care of that:

extension CGFloat {
    var toDegreesNormalized : CGFloat {
        var deg = self * 180 / .pi
        return deg >= 0 ? deg : deg + 360
    }
}

Now your code becomes

childNode(withName: "wheel")?.zRotation.toDegreesNormalized

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM