Reputation: 43
Firstly, this is a maths question, I'm not looking for code relating to image manipulation.
I have a compass rose, 0 to 360 degrees.
The needle currently points to 0 degrees.
The needle position can never exceed 360 (compassLimits.Max) and can never be below zero degrees (compassLimits.Min), these are conventional limits for any compass.
I want to move the needle to the next position, in 1-degree steps, via the shortest route.
If the next position (target) is at 10 degrees, I want to move the needle to 11 degrees, then 12 and so on, until I reach the target position.
However, if the target position is 350 degrees, I want to move the needle backwards to 359, 358 etc.
I can determine which route is the shortest, using the following (C#) algorithm:
var compassLimits = new
{
Max = 360.0,
Min = 0.0
};
var indirect = Math.Abs(compassLimits.Max - targetValue) + Math.Abs(compassLimits.Min - currentValue);
var direct = Math.Abs(targetValue - currentValue);
if (direct < indirect)
{
shortestDistance = direct;
}
else
{
shortestDistance = indirect;
}
I now need to determine if the needle should move forward or backwards to reach the target and my brain just isn't working today, so rather than repeated trial and error attempts, I thought I'd throw this out there.
Obviously, I can't rely on the target value being greater than the current value, since that works fine for moving from 0 to 10 degrees, but fails when moving from 0 to 350 degrees.
The shortestDistance variable above, is always a positive value, as I'm using Math.Abs() to calculate it.
So how do I determine the direction the needle should move?
Upvotes: 1
Views: 149
Reputation: 407
It depends of direct and indirect and if target value if greater than currentValue, so you had the two half of the answer:
if (direct < indirect)
{
shortestDistance = direct;
if (currentValue < targetValue)
{
Console.WriteLine("Forward");
}
else
{
Console.WriteLine("BackWard");
}
}
else
{
shortestDistance = indirect;
if (currentValue < targetValue)
{
Console.WriteLine("BackWard");
}
else
{
Console.WriteLine("Forward");
}
}
Upvotes: 1