I want to move GameObject from position A to B with Vector3.MoveTowards
within x seconds and in a coroutine function. I know how to do this with Vector3.Lerp
but this time would prefer to do it with Vector3.MoveTowards
since both functions behave differently.
With Vector3.Lerp
, this is done like this:
IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
float counter = 0;
//Get the current position of the object to be moved
Vector3 startPos = fromPosition.position;
while (counter < duration)
{
counter += Time.deltaTime;
fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
yield return null;
}
}
I tried to do the the-same thing with Vector3.MoveTowards
, but it's not working properly. The problem is that the move finishes before the x time or duration. Also, it doesn't move smoothly. It jumps to the middle of both positions than to the end of position B.
This is the function that uses Vector3.MoveTowards
with the issue above:
IEnumerator MoveTowards(Transform objectToMove, Vector3 toPosition, float duration)
{
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
Vector3 currentPos = objectToMove.position;
float time = Vector3.Distance(currentPos, toPosition) / duration;
objectToMove.position = Vector3.MoveTowards(currentPos, toPosition,
time);
Debug.Log(counter + " / " + duration);
yield return null;
}
}
How do you move GameObject from position A to B with Vector3.MoveTowards
within x seconds and in a coroutine function?
Please do not suggest Vector3.Lerp
as that's not what I want to use.
EDIT:
Replacing
float time = Vector3.Distance(currentPos, toPosition) / duration;
with
float time = Vector3.Distance(startPos, toPosition) / (duration * 60f);
works but introduces a problem when focus is shifted from Unity to another application. Doing that causes the movement to not finish. Calculating it every frame instead of once before starting the timer seems more reasonable.
MatrixTai's answer fixed both problems.