Search Unity

Moving 2DRigidbody in Coroutine

Discussion in 'Physics' started by path14, May 16, 2020.

  1. path14

    path14

    Joined:
    Apr 9, 2017
    Posts:
    113
    Hi All,

    I'm having this 'issue' with moving a 2D rigidbody in a coroutine. Currently it's not reaching the target. Newpos.y is 6.5 and it goes as far as 6.46. In general I'm also wondering what the best practice is with moving rigidbodies in coroutines. (I've tried with rb.position instead of transform.position, but no luck).

    Any feedback is appreciated :)

    Code (CSharp):
    1.  
    2.     private IEnumerator Rush()
    3.     {
    4.         newPos = (Vector2)transform.position + (Vector2)transform.up * 1;
    5.  
    6.         timer = 0;
    7.  
    8.         while(true)
    9.         {
    10.             timer += Time.deltaTime;
    11.  
    12.             Vector2 move = Vector2.MoveTowards(transform.position, newPos, timer / 5);
    13.  
    14.             rb.MovePosition(move);
    15.  
    16.             yield return new WaitForFixedUpdate();
    17.  
    18.             if((Vector2)transform.position == newPos)
    19.             {
    20.  
    21.                 yield break;
    22.  
    23.             }
    24.         }
    25.     }