Lerp for rotation

I had trouble finding a function to lerp rotations, so I wrote my own. There is probably a better way to do this, or at least a more efficient way to write the function, but this is how I did it.
This can be used to interpolate angles, like smoothing out an object targeting the mouse.

function lerp_angle(a, b, t)
	local full_rot = (math.pi*2)
	
	a = a % full_rot
	b = b % full_rot
	
	local diff = ( b - a ) % full_rot

	local corrected = 0
	if diff < math.pi then
		corrected = diff
	else
		corrected = diff - full_rot
	end
	
	return (a + corrected * t) % full_rot
end

(I should go without saying but just in case) Licence for this code is CC0. You can use it however you want.

7 Likes

In case you need it for vectors, you have vmath.slerp()

6 Likes

Yeah, I’m not sure why we even expose that function (lerp for quaternions), other than for matematical completeness.
I personally haven’t used a lerp with quaternions, as it lerps the 4 values.
The slerp (spherical interpolation), respects the rotation, and keeps the length as 1 through out.

4 Likes