Lerp isn't completing itself

Hello,

I have this script that moves the player to the mouse position when clicked. The problem is that the lerp is not completed, and the character moves only a bit after each click. Any help?

if (Input.GetMouseButtonDown(0))
	{
		var hit: RaycastHit;
		var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		
		if (Physics.Raycast(ray, hit)) {
			transform.position = Vector3.Lerp (transform.position, hit.point, Time.deltaTime * smooth);
		}
	}

This is a very common mistake. Assuming this code is within Update() then, on the frame in which your mouse button is clicked, you are moving “Time.deltaTime * smooth” (a small number) of the fraction of the distance from the current position to the hit point. That’s it.

It’s unclear what behaviour you really meant, but try changing GetMouseButtonDown to GetMouseButton. Then hold the button down to move.

if (Input.GetMouseButtonDown(0))
{
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, hit)) {
            StopAllCoroutines();
	    StartCoroutine(Motion(hit.point));
        }
    }

and then add this method:

IEnumerator Motion(Vector3 position)
{
	float t = 0;
	while(t < 1)
	{
		t += Time.deltaTime;
		transform.position = Vector3.Lerp (transform.position, position, Time.deltaTime * smooth);
		yield return null;
	}
}

This will move for 1 second, and should be enough depending on your smooth factor.

You could add an if statement saying if the distance from the hit point is ridiculously small, say .001f, then set the transform’s position equal to the hit point.