# Vector3.MoveTowards jumping all at once, not gradually

Hi,

This is probably a really basic question but I can’t figure out what’s going on. I want my player to move gradually to the destination point over multiple frames with a single keypress using MoveTowards (i.e. press and release the button once) I have the following three functions. The player is moving all of a sudden to the destination. I have the following three functions:

``````    void Start()
{
destn = transform.position;
}
``````
``````    void Update()
{
if(Input.GetKeyDown(KeyCode.LeftArrow) && goon)
{
{
StartCoroutine(movePlayer());
}
}
}
``````
``````    IEnumerator movePlayer()
{
destn.x = -2f;
while(goon)
{
if(Vector3.Distance(transform.position, destn) > 0.001f)
{
print("The distance is: " + Vector3.Distance(transform.position, destn));
print("X: " + destn.x + ", Y: " + destn.y + ", Z: " + destn.z);
transform.position = Vector3.MoveTowards(transform.position, destn, 1f * Time.deltaTime);
} else
{
transform.position = destn;
goon = false;
}
}

print("Left Arrow Was Pressed!");
return null;
}
``````

Any advice will be much appreciated

Your coroutine doesn’t yield in the while loop, so that loop will iterate until its end condition is met, all within a single frame of your game.

Loops do not wait for your game to move to the next frame between iterations (if you think about it, that would make a lot of things impossible). You can make them wait if they are a part of a coroutine and you use the yield keyword (something like “yield return null;” where you want to wait for the next frame). This only works in coroutines.

1 Like

That’s brilliant, thank you so much. Shifted my ‘return null’ inside the while loop and changed it to ‘yield return null’ and it works perfectly!

1 Like