-2

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

SagiZiv
  • 932
  • 1
  • 16
  • 38
  • I think you should take note of the starting position and then keep from that to end, now you’re lerping from current position to the end and changing time. That causes non-linear movement – Sami Kuhmonen Oct 05 '18 at 08:42
  • I copied the code from the link that I added (with minor modifications). I don't understand why it doesn't moves correctly... – SagiZiv Oct 05 '18 at 08:45
  • Yes, and one thing you changed was exactly the thing I mentioned – Sami Kuhmonen Oct 05 '18 at 08:46
  • wow, I didn't noticed that I did it. I see it now. Thank you very much. next time I would just copy paste without modify.... – SagiZiv Oct 05 '18 at 08:48
  • 1
    Not sure why you had to ask this again. Before saying "it's not a duplicate", read the actual duplicate. You will notice `Vector3 startPos = fromPosition.position;` which get's the starting position outside the `while` loop. – Programmer Oct 05 '18 at 10:46

1 Answers1

1

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.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74