# lerp() goes to negative infinity

Attention Topic was automatically imported from the old Question2Answer platform.

I used this code to implement lerp() in c#

``````float lerp(float firstFloat, float secondFloat, float by){
//return firstFloat * (1 - by) + secondFloat * by;
return firstFloat + (secondFloat - firstFloat) * by;
}
``````

and this code to change player’s speed

``````    void getDirection(float delta){
float dir = 0;
if (Input.IsActionPressed("move_left")){
dir --;
}
else if (Input.IsActionPressed("move_right")){
dir ++;
}

if(dir > 0){
velocity.x = lerp(velocity.x , speed, 0.02f);
}
else if (dir < 0){
velocity.x = lerp(velocity.x , -speed,  0.02f);
}
else{
velocity.x = lerp(velocity.x, 0, 0.2f);
}
}
``````

every thing works fine player accelerate and deaccelerate as expected, but problem is that it deaccelerate to -∞ (negative infinity)

I don’t know what’s wrong

bloodsign | 2021-02-23 13:11

try this , you should stop the lerp whenever it reaches 0

``````if(dir > 0){
velocity.x = lerp(velocity.x , speed, 0.02f);
}
else if (dir < 0){
velocity.x = lerp(velocity.x , -speed,  0.02f);
}
else{
if (velocity.x > 0) {
velocity.x = lerp(velocity.x, 0, 0.2f);
}
}
``````

but what if velocity is negative… btw i understood what you are trying to say but problem now arises that it never reaches perfectly 0. I tried to round it to zero but not succeded

Vikrant | 2021-02-24 14:37

you can check if it’s smaller than or equal zero , also there’s a function called `is_zero_approx()` and `is_equal_approx()` in gdscript to check if the numbers are nearly equal a value and returns true , you can search it in C# api

Whalesstate | 2021-02-24 14:42

and btw the reason it will never reach zero is because lerp always return
value1 + (value2 - value1) * amount [ 0.2 ] . means it will keep multiply value - difference with 0.2 forever , so you need to stop the lerp whenever it reach a small number like 0.01 and then set velocity.x to zero

Whalesstate | 2021-02-24 15:35

Ok this helped alot, i used this to check if it is approx 0

``````private bool myApproximation(float a)
{
return (Math.Abs(a) < 0.25f);
}
``````

and if it so then i stopped executing lerp()

If you know any better way to do so pls consider contacting me

Vikrant | 2021-02-25 12:10