Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lerping from position to position

Tags:

c#

position

lerp

I need to make a picture box to lerp from position to position (like you can do that in unity).
How can I do that , is there a built-in function?
thanks :)

like image 416
Paz Haviv Avatar asked Oct 09 '15 18:10

Paz Haviv


2 Answers

Linear interpolation (lerp) is actually a pretty easy function to implement. The equation is

float Lerp(float firstFloat, float secondFloat, float by)
{
     return firstFloat * (1 - by) + secondFloat * by;
}

A higher order Lerp just wraps lower order lerps:

Vector2 Lerp(Vector2 firstVector, Vector2 secondVector, float by)
{
    float retX = Lerp(firstVector.x, secondVector.x, by);
    float retY = Lerp(firstVector.y, secondVector.y, by);
    return new Vector2(retX, retY);
}

The DirectX SDK has all manner of math functions like Unity, but that's a lot of overhead to bring in just for Lerp. You're probably best off just implementing your own.

like image 98
Greg Bahm Avatar answered Nov 02 '22 23:11

Greg Bahm


Greg Bahm wrote inverted lerp equation firstFloat * by + secondFloat * (1 - by), where firstFloat is the secondFloat and secondFloat is the firstFloat.

In fact, corrent lerp equation is:

firstFloat * (1 - by) + secondFloat * by

But the fastest way to linear interpolation is:

firstFloat + (secondFloat - firstFloat) * by

That's 2 additions/subtractions and 1 multiplication instead of 2 addition/subtractions and 2 multiplications. Lerp for Vector2 is correct.

Also, the fastest way is less precise (thank you, cid):

Imprecise method, which does not guarantee v = v1 when t = 1, due to floating-point arithmetic error. This method is monotonic
This form may be used when the hardware has a native fused multiply-add instruction. https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support

like image 24
Bodix Avatar answered Nov 02 '22 23:11

Bodix