# Chapter 2 Challenge 3

I have a question regarding the rotate(sprite:direction:rotateRadiansPerSec:) method suggested in the solution of the Challenge 3 of the Chapter 2.

func rotate(sprite: SKSpriteNode, direction: CGPoint, rotateRadiansPerSec: CGFloat) {
let shortest = shortestAngleBetween(angle1: sprite.zRotation, angle2: velocity.angle)
let amountToRotate = min(rotateRadiansPerSec * CGFloat(dt), abs(shortest))
sprite.zRotation += shortest.sign() * amountToRotate
}

I tried the challenge myself but wasn’t being able to sort out one problem, so I took the help from the solution.
Could someone please be kind enough to explain in brief how the last two statements of this method are working from the geometry perspective ?
It is probably very simple but somehow I am not quite getting it.

amountToRotate is the smaller of two angles: one is the rotation speed times the time interval (rotateRadiansPerSec * dt); the other is the remaining angle left to rotate, calculated in the line above and called shortest.

the sprite.zRotation is then changed by adding the amountToRotate, with the direction +/- being the sign of the shortest angle.

1 Like

Thanks a lot for having a look at my query and answering.

One of my main confusions were understanding the particular one you have mentioned as “direction +/- being the sign of the shortest angle.” This is the last bit of thing that I want to understand from geometry perspective.

I guess I need to brush up my geometry, especially on the angles degree / radian mapping in order to do that, right ???

The function called shortestAngleBetween returns an angle, which is positive to go left (counter clockwise), and negative to go right (clockwise).

For testing, you could skip the calculation with rotateRadiansPerSec, and just do the full rotation every time. You would then just add the angle returned to the zRotation:

``````sprite.zRotation += shortest
``````

If the angle is negative, it will rotate right, and if it is positive, it will rotate left.

Once you get that down, then you can calculate the amountToRotate, so you don’t do the whole thing at once. But you still want to go in the direction that shortest indicates, so you multiply by the sign of shortest, so the change is in the same direction as shortest.

sprite.zRotation += shortest.sign() * amountToRotate

It would be same whether it was in degrees or in radians.

1 Like

Thanks a lot. This clears much of the confusion now.

This topic was automatically closed after 166 days. New replies are no longer allowed.