0 votes

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

Godot version 3.2.3
in Engine by (188 points)

how about calling clamp() ?

1 Answer

0 votes
Best answer

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);
    }
}
by (272 points)
selected by

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

thanks for your attention

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

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.