# Adjust angle towards another angle

## Recommended Posts

So I have two angles, a1 and a2, in the range [0, 2*PI). I want to adjust a1 .01 radians towards a2. How do I determine if I need to add or subtract .01 radians?

I understand that I can calculate the two differences thusly:

difference1 = Math.abs(a2 - a1)

difference2 = 2*PI - difference1

But even given those two differences, I don't see how to make the leap in the right direction. I can't think of a simple way of doing it that doesn't involve looking at things on a case by case, per quadrant basis.

Edited by aptpatzer

##### Share on other sites
#include <cmath>

float const Pi = std::atan(1.0f) * 4.0f;

float angle_diff(float a1, float a2) {
float diff = a2 - a1;

if (diff >= Pi)
return diff - 2.0f * Pi;

if (diff < -Pi)
return diff + 2.0f * Pi;

return diff;
}

float limited_angle_diff(float a1, float a2, float max) {
float d = angle_diff(a1, a2);

if (std::abs(d) > max)
return d > 0 ? max : -max;

return d;
}

You should consider using unit-length complex numbers instead of angles, because rotations are more naturally expressed that way. If you were doing that, this is what the could would look like:

#include <complex>

typedef std::complex<float> Complex;

Complex limited_rotation_towards(Complex z1, Complex z2, Complex max) {
Complex r = z2 / z1; // Look, ma, no special cases!

if (std::abs(r.imag()) > max.imag())
return r.imag() > 0 ? max : conj(max);

return r;
}


Edited by alvaro

##### Share on other sites

Is the complex just a mapping of (real, imaginary) -> (x, y) for this case?

##### Share on other sites
35 minutes ago, aptpatzer said:

Is the complex just a mapping of (real, imaginary) -> (x, y) for this case?

A complex number is a number of the for a+b*i, where i = sqrt(-1). You can identify the point (x,y) with the complex number x+y*i, and a rotation of angle a with the complex number cos(a)+sin(a)*i. Then applying a rotation around the origin is simply multiplication. That makes a lot of operations very convenient.

Let me know if that's still not clear enough.

##### Share on other sites

Yep it's clear. Euler's formula traces a unit circle in the complex plane. I'll have to implement a complex class and overload some arithmetic operators for it. That should be fun and useful though. Thanks for the help sir.

Edited by aptpatzer

##### Share on other sites

Incidentally the same mapping also applies to the higher-order complex numbers like quaternians, but thinking of orientation as a four-dimensional value is a little more difficult.

## Create an account

Register a new account

1. 1
2. 2
Rutin
15
3. 3
4. 4
5. 5

• 9
• 9
• 14
• 12
• 10
• ### Forum Statistics

• Total Topics
633269
• Total Posts
3011148
• ### Who's Online (See full list)

There are no registered users currently online

×