Maury Markowitz
Maury Markowitz

Reputation: 9303

SpriteKit rotation confusion

I'm trying to understand, in a general way, how to address the flipping that occurs when using atan/atan2 and SK's zRotation.

My Swift code catches the mouseDown and then calculates the angle between the current location and the click using this little function:

func angleBetweenPointOne(PointOne: CGPoint, andPointTwo PointTwo: CGPoint) -> Double {
    let xdiff = CDouble(PointTwo.x - PointOne.x)
    let ydiff = CDouble(PointTwo.y - PointOne.y)
    let rad = atan2(ydiff, xdiff)
    return rad - 1.5707963268       // convert from atan's right-pointing zero to CG's up-pointing zero
}

Now I do this:

let action = SKAction.rotateToAngle(CGFloat(angle), duration:0.2)
PlayerSprite.runAction(action)

Most of the time it works fine, the sprite cleanly rotates to the new angle. This works for most points you might click/touch. However, if the clicks cross the -ve Y axis - i.e. the click was just below the sprite and the next is just above, the angle is not a small one but 360 minus the angle. So the sprite rotates the long way.

I'm trying to understand how to address this so I don't keep making the same mistake over and over.

Upvotes: 2

Views: 1400

Answers (1)

Andrew Knoll
Andrew Knoll

Reputation: 211

Replace the line

let action = SKAction.rotateToAngle(CGFloat(angle), duration:0.2)

with

let action = SKAction.rotateToAngle(CGFloat(angle), duration:0.2, shortestUnitArc:true)

What's happening is that when the clicks cross the negative-X axis, the angle returned from atan2() changes from "something close to π" to "something close to ," or vice versa. You've offset this by a quarter turn, so it shows up on the negative-Y axis instead. Both π and yield the same rotation of the sprite, but when the action calculates the transition between them, it sees a difference of , and inserts intermediary points appropriately.

The shortestUnitArc parameter allows you to require a check to see if the other way is shorter, and if so, rotate that way.

Upvotes: 5

Related Questions