- Home /
lerp from a to moving position
lerp usually works for me but it seem it has lag when TO position is moving object, like ball catching another ball which is moving too.
so is there a way to modify this function to make it work better ,even though i don't know much of how it work.
IEnumerator MoveFromTo(Vector3 pointA, Vector3 pointB,float time)
{
if (!moving) { // Do nothing if already moving
tT=Time.time;
moving = true; // Set flag to true
float tP = 0f;
while (tP < 1.0f) {
tP += Time.deltaTime / time; // Sweeps from 0 to 1 in time seconds
transform.position = Vector3.Lerp(pointA, pointB, tP); // Set position proportional to t
yield return null; // Leave the routine and return here in the next frame
}
moving = false; // Finished moving
Debug.Log("done");
tT=Time.time-tT;
}
}
I'm not sure I fully understand the issue, but the bottom line is that if you want it to follow a moving object you need to keep on using the position of that object. Whereas, it looks to me like this coroutine moves to a fixed position (point B).
Presumably you're passing in the position of your target as point B. But if (and as soon as) the target moves, while the coroutine is running, then it's no longer at the position to coroutine is moving to. What you're doing is moving to the position the target was at when you started moving. Is that what you mean by "lag"?
The coroutine needs to know what object its following, so that every time it yields it can check the position of that object again.
But then you'll have other issues. , Such as you'll probably want to use $$anonymous$$oveTowards to move from the current position towards the target, rather than Lerping between a fixed position and a moving one. And do you really want to do the movement in a fixed amount of time? (this won't result in smooth movement, when the target is moving).
Yes, if you know or can work out where the target is going to be in X seconds, then you can make the other object move to that position during that time. But that's not the same as following the target.
To properly follow the target, you could make it move towards the target on each update, by a distance that's some multiple of Time.deltaTime. But then the speed will be constant rather than how long it takes to get there.
thank i will try one more question, how can i break the while loop from outside of the function
put another bool outside of the function to check whether it needs to break,
while (tP < 1.0f && !isBreak)
change value of isBreak from outside of the function