0

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;
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
blockay
  • 17
  • 8
  • 1
    You have your pluses and minuses the wrong way round. – user207421 Mar 06 '15 at 23:44
  • I sure do lol, thanks for helping everyone. I'll try not to make such a silly mistake next time. But I'm still having problems with the sprite 'jumping' – blockay Mar 07 '15 at 04:13

1 Answers1

2

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;
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • Oh man what a sloppy mistake. thanks for correcting me. But I'm still having problems with the sprite 'jumping'. This is the line I use to interpolate the rotation name.angle = (name.getBody().getTransform().getRotation() * alpha + name.prevAngle * (1.0f - alpha)); Besides that, I just set the sprite to the interpolated rotation and and position. I tried setting the origin of the sprite to the center but that didn't change anything. – blockay Mar 07 '15 at 04:12