Calculate distance from one angle to another in different directions

69 Views Asked by At

I've an object whose rotation degrees are locked to be in the interval $[0, 360)$. I want to calculate the distance in two different directions, so that I can decide which is the shorter route for a spinning. That is, in a -1 scale (anticlockwise), or 1 scale (clockwise), while rotating (or "spinning") my object until the final angle.

For example, say I've ${ x = 0, y = 90 }$. My final (target) angle is $x$. If I go from $y$ to $x$ by incrementing the current object's angle by +1, how many increments will it take to reach $x$? If I instead increment the current object's angle by $-1$, how many increments will it take to reach $x$?

The delta $y - x$ only tells one direction. I need to know the delta if I spin until $x$ from left and the delta if I spin until $x$ from right.

Illustration:

Arc


Thanks @Souparna and @RossMillikan. I tried this equation in JavaScript:

{
  let x = 50, y = 359;
  let xy = x - y, yx = y - x;
  xy = xy < 0 ? xy + 360 : xy;
  yx = yx < 0 ? yx + 360 : yx;
  xy < yx // if true, go clockwise
}

That should yield true. It looks like it works.

1

There are 1 best solutions below

3
On BEST ANSWER

The two angles are $x-y$ and $y-x$. One of those will be negative, so add $360$ to it. Then compare the two values and take the smaller. For example, if $x=10, y=200, y-x=190, x-y+360=170$ and you should go clockwise.