Lerp is instant. How to fix?
I'm trying to interpolate a float value from one value to another value over a time. These 3 are parameters for the function containing the Lerp. Here is the code.
//Function to scale player up and down
function scalePlayer(scaleTo : float, timeUp : float, timeDown : float) {
player.transform.localScale = new Vector3(Mathf.Lerp(objectScale[0], scaleTo, Time.deltaTime/timeUp), Mathf.Lerp(objectScale[1], scaleTo, Time.deltaTime/timeUp), 0);
yield WaitForSeconds(timeUp);
player.transform.localScale = new Vector3(Mathf.Lerp(scaleTo, objectScale[0], Time.deltaTime/timeDown), Mathf.Lerp(scaleTo, objectScale[1], Time.deltaTime/timeDown), 0);
}
I've looked through all online resources and can't find anything that fixes the problem. The array being used is one that stores the players original size. The first Lerp interpolates the players scale between their starting scale and their new scale, the second one scales them back. The game is rhythm based so I want the players size to change with the beat. The value jumps up instantly when the function is called and the second part after the waitforseconds is never even called. What am I doing wrong?
Answer by Pharaoh_ · Apr 26, 2016 at 06:56 PM
Is this an IEnumerator? Mathf.Lerp should be used in a timely fashion, e.g. a coroutine or an Update() function, otherwise it will instantly change.
Can you walk me through adding a coroutine to my function? I know you can't use wait functions inside update functions so I cannot use update.
Answer by Barsonax · Apr 26, 2016 at 07:13 PM
Sometime ago i did something similar with smoothdamp. A good way to do this is to make a coroutine which will repeat X times until you reached your destination. My code looks like this:
IEnumerator LerpToPosition2DCoroutine(Vector2 position)
{
while (Vector2.Distance(transform.position, position) > 0.02f)
{
transform.position = Vector2.SmoothDamp(transform.position, position, ref _currentVelocity,_smoothing);
transform.position = transform.position + new Vector3(0, 0, -10); //In my case iam using this for a camera so i obviously dont want the camera to sit at the same height as the rest of the scene
yield return StartCoroutine(CoroutineUtils.WaitForRealSeconds(0.005f)); //This is the time the function will wait between excecuting the next iteration
}
}
Then i simply do this to start it: StartCoroutine(LerpToPosition2DCoroutine(position));
Should be quite easy to change this to use lerp. I hope this helps.
Your answer
![](https://koobas.hobune.stream/wayback/20220612075649im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Trying to use coroutines in order to use Mathf.Lerp, Lerp instantly jumps values 0 Answers
Speed Increase Power up 1 Answer
what does this error mean? javascript 0 Answers
Tree Chopping/Harvesting cooldown 0 Answers
Any way to use UI on a screen renderer? 0 Answers