Vector3.MoveTowards Problem

Hello Guys! I tried to create a script that moves the character to the closest point (tagged LeapPoint) when the F key is pressed. But character doesnt smoothly travel the whole distance to the point when pressed, only moves instantly to certain distances when pressed.

So instead of smoothly moving towards the point over time when F is pressed, it suddenly jerks towards the point a fraction of the way.

I know that MoveTowards needs to be in the update function but then I wouldnt know how to play it when F is pressed. Can someone help me!!!

public GameObject myChar;
public float speed = 1f;
public Transform target;


void Start () {
	myChar = this.gameObject;
}

void Update ()
{
	FindClosestPoint ();

	if (Input.GetKeyDown (KeyCode.F))
	{
		 MoveToPoint()
	}
}
	
void MoveToPoint(){

	float step = speed * Time.deltaTime;

	myChar.transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}

public GameObject FindClosestPoint() 
{
	GameObject[] points;
	points = GameObject.FindGameObjectsWithTag("LeapPoint");
	GameObject closest = null;
	 
	float distance = Mathf.Infinity;
	Vector3 position = transform.position;
	foreach (GameObject point in points) {
		Vector3 diff = point.transform.position - position;
		float curDistance = diff.sqrMagnitude;
		if (curDistance < distance && point.GetComponent<LeapPoint>().hasLeaped == false) {
			closest = point;
			distance = curDistance;
			target = closest.transform;
		}
	}
	return closest;
}

}

You need a Coroutine for this:

void Update ()
{
	FindClosestPoint ();
	if (Input.GetKeyDown (KeyCode.F))
	{
		StartCoroutine(MoveToPoint());
	}
}

IEnumerator MoveToPoint()
{
	float waitTime = 0.04f;
	//small number to make it smooth, 0.04 makes it execute 25 times / sec

	while (true)
	{
		yield return WaitForSeconds(waitTime);
		//use WaitForSecondsRealtime if you want it to be unaffected by timescale
		float step = speed * waitTime;
		transform.position = Vector3.MoveTowards(transform.position, target.position, step);

		if (something) //add a check here or in the "while" to break out of the loop!
		{
			break;
		}
	}
}

Hi,
You should put the move in the update and link it to a boolean which changes when you hit F.

 public GameObject myChar;
 public float speed = 1f;
 public Transform target;
bool move;
 
 void Start () {
     myChar = this.gameObject;
 }

 void Update ()
 {
     FindClosestPoint ();

     if (Input.GetKeyDown (KeyCode.F))
     {
          move = true;
     }

     if(move == true)
     {
     float step = speed * Time.deltaTime;
     myChar.transform.position = Vector3.MoveTowards(transform.position,     target.position, step);
      }

if( transform.position== target.transform.position)
     {
     move = false;
      }

 }

Hope that helps,