- Home /
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);
}
}
Answer by tanoshimi · Aug 29, 2014 at 06:48 PM
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.
yes, in this case it works, but I need to move with one click
Answer by KMKxJOEY1 · Aug 29, 2014 at 06:48 PM
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.
Do I put the second part outside of the Update function? Because if I do, I get errors!
$$anonymous$$aybe because it is C# syntax (I think) Can you translate it to Js?
function Update ()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit))
{
StopAllCoroutines();
$$anonymous$$otion(hit.point);
}
}
}
function $$anonymous$$otion(position : Vector3)
{
var t : float = 0;
while(t < 1)
{
t += Time.deltaTime;
transform.position = Vector3.Lerp (transform.position, position, Time.deltaTime * smooth);
yield;
}
}
"Should" be translated into .js if i haven't failed :)
Answer by kacyesp · Aug 29, 2014 at 06:49 PM
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.
This is incorrect. Lerp will interpolate the Vectors and will reach the destination if you plug in the right ratio value $$anonymous$$G. 1. $$anonymous$$any people have a misunderstanding of how Lerp and SLerp work.