1

I'm making a game in JavaScript in which I need to interpolate the result from the Math.atan2 function (which wraps around at 180 degrees to -180 degrees). Currently I just a lerp function, shown below

function lerp(a, b, t) {
    return a + (b - a) * t
}

rotation = lerp(rotation, newRotation, 0.2)

The problem with this implementation is that when newRotation wraps around, rotation spins all the way around the opposite way to reach it. I attempted to solve this by checking both their signs before deciding to lerp or not

if (Math.sign(rotation) == Math.sign(newRotation)) {
     rotation = lerp(rotation, newRotation, 0.2)
} else {
     rotation = newRotation
}

And while it no longer spins all the way around, if newRotation is even somewhat far from rotation, then it akwardly jumps to newRotation and defeats the whole purpose of interpolation.

So my question is if there's a way to have rotation smoothly transition to newRotation through the wraparound point.

RKM
  • 43
  • 6

0 Answers0