- Home /
 
Why is my Mathf.Lerp not lasting for the intended duration, even though I'm not using Time.time as the t variable?
just figured this out myself but hadn't found a direct answer here so I thought I'd share for other people making the same mistake. I'll post the answer myself if it gets approved in the moderation queue.*
Why is my Lerp not lasting the intended duration?
 using UnityEngine;
 using System.Collections;
 
 public class TestingLerpScript : MonoBehaviour {
 
     void Start(){
         StartCoroutine(LerpCoroutine(10f, 5f, 0.05f));
     }
     
 
     IEnumerator LerpCoroutine(float finalX, float duration, float marginOfError){
 
         Debug.Log (duration);
 
         float startTime = Time.time;
         float currentX = 0f;
 
         while( (currentX != finalX) && (Mathf.Abs(finalX-currentX))>marginOfError)
         {
             float localTime = Time.time-Time.deltaTime - startTime;
             float percentCovered = localTime/duration;
 
             currentX = Mathf.Lerp (currentX, finalX, percentCovered);
 
             yield return null;
         }
 
         Debug.Log(Time.time-startTime);
         
     }
 }
 
               Thank You.
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Lucanio · Jan 02, 2014 at 05:35 AM
The problem is you're using currentX as a starting position each time the Lerp is called, but the starting position should remain the same. This is what it should be instead:
        float startTime = Time.time;
         float startX = 0f;
         float currentX = startX;
 
         while( (currentX != finalX) && (Mathf.Abs(finalX-currentX))>marginOfError)
         {
             float localTime = Time.time-Time.deltaTime - startTime;
             float percentCovered = localTime/duration;
 
             //currentX = Mathf.Lerp (currentX, finalX, percentCovered);
             currentX = Mathf.Lerp (startX, finalX, percentCovered);
 
             yield return null;
         }
 
              Your answer