1
\$\begingroup\$

I have one object that I want to rotate to a certain angle with 'smooth' rotation. I looked up on how to solve that and I came up with this: 1

But how do I know in what way to rotate, positive or negative? According the the picture on ex. 1, I need to rotate positively because it is the closest way for me to rotate. And on the second it is the negative way. But how do I know this? I've tried several solutions but I can't seem to find anything that is correct.

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

There are different ways to represent angles and you didn't mention which you use. So let's assume that you represent the directions of angles measured in Radiants between 0π and 2π and any angles outside of that allowed range are automatically transformed back into it by adding/subtracting 2π until they fit again.

When the difference between this.angle and other.angle is less than 1π, the case is trivial.

 if (this.angle > other.angle) {
      this.angle -= TURN_SPEED;
 } else {
      this.angle += TURN_SPEED;
 }

But this obviously doesn't work when the two angles are close to each other, but on different sides of the 0-angle, like on 1/4π and 7/4π. But you can detect that case by checking the difference between the angles. When it's the case, it will always be larger than 1π. That means when the difference is > π, you just need to invert the direction.

if ( abs(this.angle - other.angle) < PI) {
     if (this.angle > other.angle) {
        this.angle -= TURN_SPEED;
    } else {
        this.angle += TURN_SPEED;
    }
} else {
     if (this.angle > other.angle) {
        this.angle += TURN_SPEED;
    } else {
        this.angle -= TURN_SPEED;
    }
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .