Search code examples
javaandroidlibgdxnormalizeradians

How to normalize an angle between -π and π Java


I'm having troubles getting a normalized float to smoothly rotate some sprites. I'm using interpolation to rotate my sprites. At a certain point in the rotation the sprite will jump, at the same spot every time.

name.angle = (name.getBody().getTransform().getRotation() * alpha + name.prevAngle * (1.0f - alpha));

I've looked online and found a couple ways to normalize an angle between -pi and +pi but I can't get them to work in my situation.

The following doesn't work

if (name.angle > Math.PI)
    name.angle += 2 * Math.PI;
else if (name.angle < -Math.PI)
    name.angle -= 2 * Math.PI;

The following does work

name.angle = name.angle < 0 ? MathUtils.PI2 - (-name.angle % MathUtils.PI2) : name.angle % MathUtils.PI2;

Solution

  • In your first code snippet you write

    if (name.angle > Math.PI)
        name.angle += 2 * Math.PI;
    

    This says "if name.angle is too big, make it bigger". I have fixed this by changing += to -= (and changing -= to += in the next bit). I have also replaced if with while. That way it will still work if the initial angle is more than 2 pi too big/small. The correct code is:

    double pi = Math.PI;
    while (angle > pi)
        angle -= 2 * pi;
    while (angle < -pi)
        angle += 2 * pi;