- Home /
The question is answered, right answer was accepted
Why doesnt Vector2.Lerp work?
I have an object that i want to Lerp left and right across the screen which is working nicely apart from the fact that is never actually reaches the destination is is coded to go to. It always stops just a little bit before it gets to where it should be.
public IEnumerator GoRight() { float elapsedTime = 0.0f;
Vector2 currentPosition = character.transform.position;
while (elapsedTime < overTime)
{
character.transform.position = Vector2.Lerp(currentPosition, new Vector2(currentPosition.x - 1000, transform.position.y), elapsedTime/overTime);
elapsedTime += Time.deltaTime;
yield return null;
}
currentPosition = character.transform.position;
}
So basically I want to move -1000 from the current position but it usually moves about 980 to 990 meaning the object is always off centre.
Is there a way to get it to Lerp exactly 1000 every time?
Answer by xxmariofer · May 21, 2019 at 07:06 PM
never reaches the destitnation because the exact iteration when elpasetime is 1 stops the while before calling the lerp method
public IEnumerator GoRight() {
Vector2 currentPosition = character.transform.position;
elapsedTime = 0;
while (elapsedTime <= overTime)
{
elapsedTime += Time.deltaTime;
character.transform.position = Vector2.Lerp(currentPosition, new Vector2(currentPosition.x - 1000, transform.position.y), elapsedTime/overTime);
yield return null;
}
currentPosition = character.transform.position;
}
Ah O$$anonymous$$ that makes sense. Any idea how that can be fixed? I'm going to have to experiment a bit more i guess.
did you try the code i posted? should fix it
Oh thanks. Thats perfect.
Sorry, i didn't actually spot a change until you said that.
Its working perfectly now, Thanks again.
Follow this Question
Related Questions
Vector3.Lerp result in "laggy" movement while running on iOS devices 2 Answers
Looking to see if the method I'm using for movement is correct or if I'm doing something wrong. 0 Answers
Difficulty with Vector2 Lerp, object jumping, not moving 2 Answers
Moving an UI element from point A to point B 1 Answer
Vector2 Lerp alternative? 2 Answers