cant lerp periodically because method call is not behaving correctly

I have this code running within a switch statement (the condition stays true during the duration of the test):

elapsedTime += animationCurve.Evaluate(Time.deltaTime);
float percentFinished = elapsedTime / duration;
transform.position = Vector3.Lerp(startPos, randomPos, animationCurve.Evaluate(percentFinished));
               
if(transform.position == randomPos)
{
    Invoke("NewRandomPos", 1f);
}

I have an object that I want to lerp continuously towards randomly set positions with a short delay before each new lerp, the method being called looks like this:

void NewRandomPos()
    {
        randomPos = new Vector3(Random.Range(-2.7f, 2.7f), Random.Range(3.2f, -4.5f), 0);
        elapsedTime = 0f;
        startPos = transform.position;
    }

My issue is that with each new lerp the object spasms out and that’s because new randomPos positions are constantly being calculated for whatever reason and I can’t find out why or how to stop NewRandomPos() from being executed constantly and to keep it to being executed a short delay after reaching it’s end position. I greatly appreciate any feedback given to me for this.

Hi!

The problem is that when adding the elapsed time, you are using the animation curve.

elapsedTime += animationCurve.Evaluate(Time.deltaTime);

Since Time.deltaTime is always quite small, if the beginning of your animation curve is a high number, it will always add this high number and basically make the animation way too fast.

The fix is quite simple, you only need to use the curve when calculating the lerped value, and not when checking the time that has passed:

elapsedTime += Time.deltaTime;

You may also want to invert your animation curve (it should end at a value of 1)

Hope this helps!

According to the documentation:

Invoke sounds like it just waits a sec(in your case), but can fire multiple times, while waiting for that second. As the documentation states, you might be better off using coroutines. I personally am not a fan of coroutines or Invokes. I hard code int values as timers, so debugging is a breeze(the only problem with this is it’s fully dependent on fps, if trying to perfectly count seconds/time). If manually setting the Application.targetFrameRate = 60;, or whatever fps you want to aim for.

So personally my code, if replicating this, would be:

if(transform.position == randomPos)
 {
     positionCounter++;
     if (positionCounter > 60)
     {
          NewRandomPos();
          positionCounter = 0;
     }
 }