Question by
darkavengerpark · Apr 14 at 06:41 AM ·
lerpienumeratorfinite-state-machine
Movement for GameObject[] in arrays jittery when using Lerp in Coroutine
I am trying to move each elements in a GameObject[]
array using Lerp
. I tried to mix and match some of the code on the internet, but I can't seem to make it work. To my understanding, it's better to use Coroutine
s instead of Update
because it's less costly, but I can't seem to make it look smooth. When change the state
variable in the Unity Editor, it changes the state successfully, but moves the objects in a glitchy, back-and-forth motion.
Could someone help me with this?
public GameObject[] hologramsGameMode;// gameObjects
public GameObject startPositionGameMode;// start positions
public GameObject[] finalPositionGameMode;// end position
[SerializeField] AnimationCurve curve;
public bool inMenuScene = true;
float time;
public float duration = 3;
public EState state;
IEnumerator Start ()
{
var wait = new WaitForSeconds(2f);
while( inMenuScene )
{
yield return wait;
switch( state )
{
case EState.ENABLE:
StartCoroutine( COEnableAnimation() );
print("StartCoroutine(COEnableAnimation())");
break;
case EState.DISABLE:
StartCoroutine( CODisableAnimation() );
print("StartCoroutine(CODisableAnimation())");
break;
}
}
}
IEnumerator COEnableAnimation ()
{
for( float t=0 ; t<1 ; t+=Time.deltaTime )
for( int i=0 ; i<hologramsGameMode.Length ; i++ )
{
hologramsGameMode[i].transform.position = Vector3.Lerp(
startPositionGameMode.transform.position ,
finalPositionGameMode[i].transform.position ,
curve.Evaluate( time/duration )
);
time += Time.deltaTime;
yield return null;
}
}
IEnumerator CODisableAnimation ()
{
for( float t=0 ; t<1 ; t+=Time.deltaTime )
for( int i=0 ; i<hologramsGameMode.Length ; i++ )
{
hologramsGameMode[i].transform.position = Vector3.Lerp(
finalPositionGameMode[i].transform.position ,
startPositionGameMode.transform.position ,
curve.Evaluate( time/duration )
);
time += Time.deltaTime;
yield return null;
}
}
public enum EState
{
ENABLE,
DISABLE
}
Comment
You need to stop the previous coroutine before starting a new one. Otherwise they overlap.