Home > Back-end >  Having trouble lerping a game object back and forth
Having trouble lerping a game object back and forth

Time:08-02

I have this hand icon that I want to move back and forth. So far I have it set up inside a coroutine like this

elapsedTime  =Time.deltaTime;
float percentageComplete=elapsedTime/desiredDuration; 
transform.position=Vector3.Lerp(startPosition,endPosition,percentageComplete);
yield return new WaitForSeconds(0.9f);
transform.position=Vector3.Lerp(endPosition,startPosition,percentageComplete);

But it's giving me this weird twitching motion after it completes one round of going from start to finish and back again. It start snapping between startPosition and endPosition.

How do I resolve this. I also want this game object to destroy itself after 3 seconds. Is it possible to use one coroutine inside another?

CodePudding user response:

Where are you resetting the elapsedTime?

You don't need a Coroutine to move the object back and forth. You can just check if your percentageComplete variable is equal to 1 and swap the start and end point. Also reset the elapsed time.

Source: https://vionixstudio.com/2021/11/03/how-to-lerp-in-unity/#How_to_check_if_lerp_is_done_in_unity

Is it possible to use one coroutine inside another?

Yes you can.

  • Related