Search Unity

Timing Move To Waypoint IEnumerator failing

Discussion in 'Scripting' started by Nigey, Apr 23, 2014.

  1. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Can anyone explain why I'm going wrong.. I don't understand :S

    Code (csharp):
    1.  
    2. float Move_Speed = 0.053f;
    3.  
    4.     IEnumerator MoveToWaypoint()
    5.     {
    6.         float dist = Vector2.Distance(currentWaypoint.transform.position, transform.position);
    7.         float time = dist / Move_Speed;
    8.  
    9.         for(float f = 0; f < time; f += Time.deltaTime)
    10.         {
    11.             Debug.Log(f + "  " + time);
    12.  
    13.             transform.Translate(((currentWaypoint.transform.position - transform.position).normalized) * Move_Speed);
    14.  
    15.             yield return new WaitForFixedUpdate();
    16.         }
    17.     }
    18.  
    It takes about 2 seconds to reach the target.. but it calculates it as 27 seconds and wont stop moving back and forth over the target until 27 seconds is up. Can anyone advise?

    Thanks
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    Probably it's becouse of you using WaitForFixedUpdate and Time.deltaTime instead of Time.fixedTime?
     
  3. mweldon

    mweldon

    Joined:
    Apr 19, 2010
    Posts:
    109
    You are calculating the time outside the loop, but your transform call is using the current position which changes every iteration. Try this instead:

    Code (csharp):
    1.  
    2. float Move_Speed = 0.053f;
    3.  
    4.     IEnumerator MoveToWaypoint()
    5.     {
    6.         Vector2 deltaPos = currentWaypoint.transform.position - transform.position;
    7.         float dist = deltaPos.length;
    8.         Vector2 moveDir = deltaPos / dist;
    9.         float time = dist / Move_Speed;
    10.  
    11.         for(float f = 0; f < time; f += Time.fixedTime)
    12.         {
    13.             Debug.Log(f + "  " + time);
    14.  
    15.             transform.Translate(moveDir * Move_Speed);
    16.  
    17.             yield return new WaitForFixedUpdate();
    18.         }
    19.     }
    20.