2017-02-15 44 views
0

所以我有一个脚本来移动游戏对象。当我移动一个gameObject的时候,它很流畅。但是当我第二次移动它时,这个动作非常缓慢,看上去有点儿缺陷。Unity GameObject在第二次移动时不能平滑运行

移动脚本中的第一个输入是对象,然后它需要移动到的位置和速度作为最后一个参数。所有坐标均基于本地位置。我使用等待,因为我想在执行第二次移动之前等待。

我试图移动其他物体两次,但它们都最终移动非常缓慢/越野车。

我不想在更新中运行此更新,这就是为什么我使用协程。

这里是我的代码:

IEnumerator MovementGentryOne() 
{ 
    StartCoroutine(Movement(GentryOne, MovementCoords.GentryOneBasin, gentryspeed)); 
    yield return new WaitForSeconds(2); 
    StartCoroutine(Movement(GentryOneArm, MovementCoords.GentryArmMoved, gentryspeed)); 
    yield return new WaitForSeconds(2); 
    StartCoroutine(Movement(GentryOnePicker, MovementCoords.GentryPickerPick, gentryspeed)); 

    yield return new WaitForSeconds(4); 
//this one is not working smooth. 
    StartCoroutine(Movement(GentryOnePicker, MovementCoords.GentryPickerStart, gentryspeed)); 
    yield return null; 
} 

private IEnumerator Movement(GameObject toMove, Vector3 position, float time) 
{ 

    float elapsedTime = 0; 
    while (elapsedTime < time) 
    { 
     toMove.transform.localPosition = Vector3.Lerp(toMove.transform.localPosition, position, (elapsedTime/time)); 
     elapsedTime += Time.deltaTime; 
     yield return null; 
    } 
    toMove.transform.localPosition = position; 
} 

任何人的想法是怎么回事?

亲切的问候

+1

你可以确认一个Movement-Coroutine已经完成,然后你开始一个新的?否则,你会为运动而战,这会造成奇怪,不平滑和不稳定的运动。 – Maakep

+0

您可以使用yield return StartCoroutine而不是在两者之间等待秒数吗? –

+0

看来协程并不会停止。使用调试器,我发现它从来没有达到声明后返回收益返回null –

回答

0

我发现答案的方法永远不会摆脱while循环。所以我编辑了while语句到: toMove.transform.localPosition!= position

+0

嗨,不要比较'Vector3'。我懒得解释为什么,但使用while循环的原始代码是实现它的正确方法。它只需要一点修改。 – Programmer

相关问题