- Home /
Lerp time and movement not in sync
I'm using vector3.Lerp to move from one position to another,but the lerp time and moevement are not in sync as lerp varies from 0 to 1.
Here's my code
Vector3 Target_Pos=new Vector3(0.18f,0,0);
float LerpTime=0.0f;
float LerpSpeed=10.0f;
void Update()
{
if(LerpTime<1.0f)
{
transform.position=Vector3.Lerp(transform.position,Target_Pos,LerpTime);
LerpTime=Time.deltatime*LerpSpeed;
}
else
{
Debug.Log("Lerp is finished");
}
}
But the object reached at position 0.18f in X before LerpTime reaching 1.0f.The object finished interpolation at a time near 0.05 to 0.1f,but the log will out only when the LerpTime variable reaches 1.0f which is areound 10 to 20 seconds after movement is finished.I need to log the exact time when the object reached its target position
Any help....?
Answer by benni05 · Feb 24, 2014 at 10:49 AM
Your LerpTime needs to approach 1f but it stays the same all the time, namely Time.deltaTime*0.18f (just considering the x component). Since deltaTime is almost a constant as well (i.e. 0.02f, the amount it takes to render the last frame).
Change to:
LerpTime += Time.deltaTime;
The transition (Lerp) will then take approx. 1 second. If you would like to speed this up, multiply by a factor, i.e.
LerpTime += Time.deltaTime * 4f;
which makes it 4x as fast, leading to a duration of 0.25 seconds.
Just to make sure you understood Lerp. The function will return the first parameter (in your case transform position) if LerpTime is zero and the second parameter if LerpTime is >=1f. And a value inbetween those parameters if >0 && <1f. Also, do not use transform.position as first parameter because this is not a constant value. Store the transform.position of your object in a variable before starting to Lerp, use this variable as the fist parameter and then you get a defined movement as described above.
It worked.I didnt knew that the first and second parameter of Lerp should be constant.Replacing transform.position with a pre captured constant position value did the trick.
Thanks a lot.. Cheers.. :-)
Ok, great. It doesn't have to be a constant. But if you are using the transform.position you are at the same time changing it easily gets confusing and you cannot exactly configure the speed in the way described. Thanks for accepting the answer. Cheers.
Your answer