Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get to an angle choosing the shortest rotation direction

Tags:

java

math

I have a character in my game that must rotate smoothly to get to a desired angle. Consider angle as the current angle and touchAngle as the desired angle which is always between 0 to 360. I want to add +1/-1 to current angle in every game update to get to the desired touchAngle. The problem is first it must chose direction and it must be between 0 to 360. this is my pseudo code:

int touchAngle;
float angle;
public void update()
{
    if ((int)angle != touchAngle) angle += ???
}
like image 768
Ali Avatar asked Aug 26 '14 12:08

Ali


1 Answers

Since you have values that are always normalized in the interval [0 360] this should not be too hard. You just need to distinguish two different cases:

angle < touchAngle
angle > touchAngle

in the first case we want to rotate counterclockwise so the update has to be angle =+ 1 (assuming that you want to turn of 1 every update cycle). In the second case we want to turn clockwise so the update should be angle -= 1.

The problem is that this is not always the shortest way to rotate. For instance if:

angle == 359
touchAngle == 1

we don't want to make all the way 358, 357, 356...instead we want to rotate counterclockwise for just 2 units: 360, 1. This can be achieved comparing the distance between the angles abs(angle - touchAngle).

If this value is bigger than 180 it means we are going the wrong way, so we have to do the way around so

if(angle < touchAngle) {
    if(abs(angle - touchAngle)<180)
       angle += 1;
    else angle -= 1;
}

else {
    if(abs(angle - touchAngle)<180)
       angle -= 1;
    else angle += 1;
}

of course all of this until ((int)angale != touchAngle). I might have made mistakes with the cases but this is the principle.

like image 60
Demplo Avatar answered Oct 12 '22 23:10

Demplo