Search code examples
unity-game-enginevectorlerp

Vector3.Lerp bug?


I know how to move GameObject over time, but I have a weird bug.

I am trying to create nice animation where the camera moves forward on button click and backward on second button click.

I am using the code from here to do the animation and have a weird problem.

This is my code:

private float time = 5, current;
public void MoveBackward()
{
   StartCotoutine(MoveTo(Vector3.zero));
}

public void MoveForward()
{
   StartCotoutine(MoveTo(new Vector3(0,0,15)));
}
private IEnumerator MoveTo(Vector3 target)
{
   current=0;
   while(transform.position!=target)
   {
     transform.position = Vector3.Lerp(transform.position, target, current/time);
     current = Mathf.Clamp(current+Time.deltaTime,0,time);
     yield return null;
   }
}

The forward motion works good, but for some reason when I try to move backwards it moves too fast. I tried to print the result (current/time) and in the backwards movement it is 0.1 (approximately) when the transform reaches to the destination.

P.S. - I am running another Cotoutine in the background (if it matters)

Do you know why it happens¿

Thanks in advance


Solution

  • The problem is in how you’re calling the lerp here:

    transform.position = Vector3.Lerp(transform.position, target, current/time);
    

    This will tell it to lerp from the current position to the end based on time, which will not be linear. You’ll need to store the start position and use that in all the lerping so you’ll get a proper interpolation.

    Also depending on how the lerp is done comparing float values might mean this never ends. It would be better to check if the lerping has finished by comparing the lerping amount.