Vector3.Lerp stick halfway

Hello,

This is probably a simple answer that I just can’t seem to find. Everything works fine in the following code, except upon pressing the tab key too fast, the movement hangs in the middle of the lerp and can’t continue its movement. I read somewhere that using Time.deltaTime isn’t necessary, but I don’t know what to substitute and keep the movement smooth.

IEnumerator FocusCoroutine (Transform target)
{
	while (Vector3.Distance (transform.position, target.position) > 0.025f) 
	{
		transform.position = Vector3.Lerp (transform.position, target.position, MoveSpeed * Time.deltaTime);
		transform.parent = target.transform;

		yield return null;
	}
	Debug.Log ("Target Reached!");
}

// called by pressing TAB key from another script
public void SwitchActive()
{
	if (TargetHumanEnabled == true) 
	{
		TargetHumanEnabled = false;
		TargetAnimalEnabled = true;
		SwitchFocus ();
	}

	else if (TargetAnimalEnabled == true) 
	{
		TargetAnimalEnabled = false;
		TargetHumanEnabled = true;
		SwitchFocus ();
	}
}

// called after SwitchActive method and once at Start of script
// calls FocusCoroutine
void SwitchFocus()
{
	Debug.Log ("Tab Key Pressed");
	GameObject targetLookAtHuman;
	GameObject targetLookAtAnimal;

	targetLookAtHuman = GameObject.Find ("targetLookAtHuman") as GameObject;
	targetLookAtAnimal = GameObject.Find ("targetLookAtAnimal") as GameObject;


	if (TargetAnimalEnabled == true) 
	{
		target = (targetLookAtAnimal.transform);
		Debug.Log ("Animal Enabled");
		StartCoroutine (FocusCoroutine (target));
	} 

	else if (TargetHumanEnabled == true)
	{
		target = (targetLookAtHuman.transform);
		Debug.Log ("Human Enabled");
		StartCoroutine (FocusCoroutine (target));
	}
}

}

Using MoveSpeed * Time.deltaTime inside Lerp is incorrect. Because, from more close you are to your target, you going to move more slowly, so, you need use Lerp like this.

Vector3 startPos= transform.position;
Vector3 endPos = target.position;
float rate = 1.0f/Vector3.Distance(startPos, endPos) * MoveSpeed;
float t = 0.0f;
while (t < 1.0f)
{
	t += Time.deltaTime * rate;
	transform.position = Vector3.Lerp(startPos, endPos, t);
	yield return null; 
}

This will move it smoothly no matter your position and distance

Well, the problem is quite simple. When you call “SwitchActive()” while there’s still a coroutine running, you will start a new coroutine. So in the end you have two or more coroutines running at the same time and each is trying to pull your player / object towards a different target. None of the coroutines can ever complete since they work against each other so you never reach any target.

As @ARKMs said your usage of Lerp is not how lerp (linear interpolation) works. You use it as a non linear smoothing function. Unless that’s exactly what you want you might want to have a look at his answer.