shortestTurnsToReachTarget method
Determines which next turn value should be used to have the least rotation
movements between current
and target
E.g: when being at 0.5 turns, should I go to 0.75 or to -0.25 to minimize the rotation ?
Implementation
double shortestTurnsToReachTarget(
{required double current, required double target}) {
final currentDegree = current * 360;
final targetDegree = target * 360;
// Determine if we need to go clockwise or counterclockwise to reach
// the next angle with the least movements
// See https://math.stackexchange.com/a/2898118
final clockWise = (targetDegree - currentDegree + 540) % 360 - 180 > 0;
double resultDegree = currentDegree;
do {
resultDegree += (clockWise ? 1 : -1) * 360 / 4;
} while (resultDegree % 360 != targetDegree % 360);
// Revert back to turns
return resultDegree / 360;
}