Why my Coroutine does unwanted pauses?
I'm using a Coroutine to launch a hook to an enemy and switch places with him on a grid. Everything is working as expected except that I have unwanted pauses between each while inside my coroutine and also at the end of the function. Here's my code:
IEnumerator HookSmooth(GridPoint2 target, float lineDrawSpeed)
{
GameObject enemy = goulsGrid[target].transform.GetChild(0).gameObject;
line.SetPosition(0, transform.position);
float counter = new float();
float dist = Vector3.Distance(transform.position, goulsGrid[target].transform.position);
Vector3 pointA = transform.position;
Vector3 pointB = goulsGrid[target].transform.position;
while (counter < dist)
{
counter += 0.1f / lineDrawSpeed;
float x = Mathf.Lerp(0, dist, counter);
Vector3 pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
line.SetPosition(1, pointAlongLine);
yield return 0;
}
counter = 0;
while (counter < dist)
{
counter += 0.1f / lineDrawSpeed;
float x = Mathf.Lerp(0, dist, counter);
Vector3 pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
line.SetPosition(0, pointAlongLine);
//Move Player
transform.position = pointAlongLine;
//Move Enemy
enemy.transform.position = Vector3.Lerp(pointB, pointA, counter);
yield return null;
}
}
The question is why I have a pause between the two while loops and also a pause at the end of my coroutine? I'm guessing that the yield return null lines are somehow producing a pause?
ps: Never use yield return 0;
. It creates garbage on the heap because "0" is a value type and need to be boxed. If you want to wait one frame, just use yield return null;
. That doesn't create any garbage.
Thanks for that, I didn't know that little nugget :)
Answer by doublemax · Dec 14, 2016 at 10:08 AM
I don't think the problem is directly related to the coroutine.
The Lerp calls expect an "t" input in the range from 0 to 1. So if "dist" is >1, you won't see any movement from the moment "counter" reaches 1.0.
@doublemax Thank you for the answer. But in that case, shouldn't the while loop stop (and with it, the coroutine as well) when "dist" is > 1 ? Is there a way to prevent very small difference numbers on "counter"?
Just suppose dist = 5. Then counter will run from 0 to 5. But only in the range from 0 to 1 will you see any movement, because Lerp will just return the endvalue for t > 1.
Try something like this (and the same of the other loop):
while (counter < dist)
{
counter += 0.1f / lineDrawSpeed;
float t = counter / dist;
float x = $$anonymous$$athf.Lerp(0, dist, t);
Vector3 pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
line.SetPosition(1, pointAlongLine);
yield return 0;
}
It works like a charm. Thank you very much for your help and explanation. I understood what I was doing wrong in my method.
Converted into an answer and moved the other comments as well ^^.