Search code examples
javascriptmathrotationradianslerp

JS | How to lerp rotation in radians?


function lerp(start, end, amt) {
    return (1-amt)*start+amt*end
}

This lerp function works perfectly with coords. I can easily lerp X from 1 to 10.
But problems appear when it comes to rotation. The rotation of an object is in radians. It can be from -3.14 to 3.14. So let's rotate our object. Starting from 0, one moment the rotation will reach to 3.14, and then... -3.14. So when lerping from 3.14 to -3.14, the object makes one full 360º rotation, (3.14, 2, 1, 0, -1, -2, -3.14) which is not good. So, can anybody tell, how to lerp the rotation?
I am using JavaScript.


Solution

  • Honestly, I don't remember how this works. But, it works.

    Its in my code to deal with lerping rotation of a player object to point towards the mouse, when the pointer angle traverses -3.14 to 3.14 this function correctly calculates the lerp across the gap. With, um, magic.

    function rLerp (A, B, w){
        let CS = (1-w)*Math.cos(A) + w*Math.cos(B);
        let SN = (1-w)*Math.sin(A) + w*Math.sin(B);
        return Math.atan2(SN,CS);
    }