【发布时间】:2020-11-28 03:48:55
【问题描述】:
我这里有一些简单的代码。我遇到的问题是图像在远离中心时以几乎两倍的速度收缩到中心(本地位置 Vector3.zero)。我相信我正在使用相同的逻辑来移动它们,所以我想知道是否有人可以告诉我是什么导致了这种行为。
也欢迎任何关于使代码本身更好的建议,但我主要关心的是插值的速度。我可能应该通过参数而不是总时间传递当前时间,但你知道...我不会每次都第一次做出完美的决定。
问题中的具体行:
IEnumerator ContractImages(float totalTime)
{
yield return m_WaitForEndOfFrame;
m_CurrentContractionTime += Time.deltaTime;
float t = m_CurrentContractionTime / totalTime;
Debug.Log(string.Format("Expansion Rate Factor: {0}", t));
Debug.Log(string.Format("Current Expansion Time: {0}", m_CurrentContractionTime));
for (int i = 0; i < m_MovingImages.Length; i++)
{
var r = m_MovingImages[i].GetComponent<RectTransform>(); //Optimize
r.localPosition = Vector3.Lerp(r.localPosition, Vector3.zero, t);
}
if (m_CurrentContractionTime < totalTime)
m_ContractionRoutine = StartCoroutine(ContractImages(totalTime));
else if (m_ContractionRoutine != null)
{
StopCoroutine(m_ContractionRoutine);
InvokeContractionComplete();
m_CurrentContractionTime = 0;
}
}
IEnumerator ExpandImages(float totalTime)
{
yield return m_WaitForEndOfFrame;
m_CurrentExpansionTime += Time.deltaTime;
float t = m_CurrentExpansionTime / totalTime;
Debug.Log(string.Format("Expansion Rate Factor: {0}", t));
Debug.Log(string.Format("Current Expansion Time: {0}", m_CurrentExpansionTime));
for (int i = 0; i < m_MovingImages.Length; i++)
{
var r = m_MovingImages[i].GetComponent<RectTransform>(); //Optimize
r.localPosition = Vector3.Lerp(Vector3.zero, m_StartingVectors[i], t);
}
if (m_CurrentExpansionTime < totalTime)
m_ContractionRoutine = StartCoroutine(ExpandImages(totalTime));
else if (m_ContractionRoutine != null)
{
StopCoroutine(m_ExpansionRoutine);
InvokeExpansionComplete();
Debug.Log("Expansion Complete: " + totalTime / m_CurrentExpansionTime);
m_CurrentExpansionTime = 0;
}
}
【问题讨论】:
-
为什么你的函数会启动另一个具有相同函数的协程?你同时跑了多少个相同的例程?
-
对于像这样的递归协程结构,通常有两个实际的例程在使用——一个正在启动,一个正在完成。例如 StopCoroutine 之后的代码在终止例程之前仍然执行。编辑:您可以通过探查器确认。