'Generic LERP for Unity
I want a generic linear interpolation function for Unity. It should work for float, Vector2, Vector3, Vector4, Color, Quaternion
Lerping requires this logic.
static T LerpGeneric<T>(T a, T b, float t)
{
return a * (1f - t) + b * t;
}
ofcourse it does not compile, and I'm not sure if this logic also works for Quaternions or not.
Solution 1:[1]
There is no simple way to do this currently. .Net generics are not like c++ templates, so you need to use a generic constraint if you want specific methods to be usable. Unfortunately no such interfaces are available for the built in types.
Providing functionality like this has been proposed multiple times. The latest would be generic math, but this is only in preview in .Net 6. I would assume that .Net 6 is not yet supported by Unity3d.
A workaround could be to delegate the add and multiply methods to delegates, i.e.
public LerpGeneric<T>(T a, T b, float t, Func<T, T, T> mul, Func<T, T, T> add)
=> add(mul(a , (1f - t)) , Mul(b , t));
But this would likely just be more complicated than providing individual implementation for each type. So I would probably just bite the bullet and provide 6 implementations. In practice it would not be a lot of code, so the maintenance overhead should be minimal.
Quaternions usually have a Lerp implementation, since that is one of the major reasons to use quaternions in the first place. Unity3ds vectors and colors also have lerp-implementations already provided, and for floats you have Mathf.Lerp.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
