我一直在研究沿着我从 Navmesh Unity3d 获得的路径的对象移动我正在使用协程,在其中我使用 while 循环控制它
public void DrawPath(NavMeshPath pathParameter, GameObject go)
{
Debug.Log("path Parameter" + pathParameter.corners.Length);
if (agent == null || agent.path == null)
{
Debug.Log("Returning");
return;
}
line.material = matToApplyOnLineRenderer;
line.SetWidth(1f, 1f);
line.SetVertexCount(pathParameter.corners.Length);
allPoints = new Vector3[pathParameter.corners.Length];
for (int i = 0; i < pathParameter.corners.Length; i++)
{
allPoints[i] = pathParameter.corners[i];
line.SetPosition(i, pathParameter.corners[i]);
}
StartCoroutine(AnimateArrow(pathParameter));
//StartCoroutine(AnimateArrowHigh(pathParameter));
}
#endregion
#region AnimateArrows
void RunAgain()
{
StartCoroutine(AnimateArrow(Navpath));
}
IEnumerator AnimateArrow(NavMeshPath path)
{
Vector3 start;
Vector3 end;
while (true)
{
if (index > 0)
{
if (index != path.corners.Length - 1)
{
start = allPoints[index];
index += 1;
end = allPoints[index];
StopCoroutine("MoveObject");
StartCoroutine(MoveObject(arrow.transform, start, end, 3.0f));
yield return null;
}
else
{
index = 0;
RunAgain();
}
}
else if (index == 0)
{
start = allPoints[index];
arrow.transform.position = allPoints[index];
index += 1;
end = allPoints[index];
StopCoroutine("MoveObject");
StartCoroutine(MoveObject(arrow.transform, start, end, 3.0f));
yield return null;
}
}
}
IEnumerator MoveObject(Transform arrow, Vector3 startPos, Vector3 endPos, float time)
{
float i = 0.0f;
float rate = 1.0f / time;
journeyLength = Vector3.Distance(startPos, endPos);
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
while (i < 1.0f)
{
// Debug.Log("fracJourney In While" + fracJourney);
arrow.position = Vector3.LerpUnclamped(startPos, endPos, fracJourney);
yield return endPos;
}
Debug.LogError("Outside While");
}
但问题是我必须以恒定的速度移动对象,但是我的对象在每个循环中都在加速,因为我必须在循环中进行移动,所以它往往会移动,直到用户想要通过输入结束它,请帮助我不明白我在协程中做错了什么,我的对象的速度正在上升,我希望它保持不变,但不知何故它不能那样工作,谢谢