Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

RigidBody2D.AddForce and Coroutine with WaitForSeconds

Discussion in '2D' started by elgatodorado, Aug 14, 2019.

  1. elgatodorado


    Apr 7, 2019
    Im trying to do a dodge back in a platformer 2d and i saw that my dodge force changes a bit every time i think is a problem with the time and the fps, if someone can explain me, here is my code:

    Code (CSharp):
    1. //Dodge(inside FixedUpdate)
    3. if (Input.GetKeyDown("s") && suelo && !esquivando && cooldown<=0)
    4.         {
    5.             esquivando = true;
    6.             myBody.velocity =;
    7.             if (transform.localScale.x ==-1)
    8.             {
    9.                 myBody.AddForce(Vector2.right * 40, ForceMode2D.Impulse);
    10.             }
    11.             else
    12.             {
    13.                 myBody.AddForce(Vector2.left * 40, ForceMode2D.Impulse);
    14.             }
    15.             StartCoroutine(Dash());
    16.         }
    18. //Coroutine
    20. IEnumerator Dash()
    21.     {
    22.         yield return new WaitForSeconds(0.05f);
    23.         myBody.velocity =;
    24.         esquivando = false;
    25.         cooldown = 0.5f;
    26.     }
    Moreover, i have a cooldown:

    Code (CSharp):
    1. //Cooldown(inside Update)
    3. cooldown -= Time.deltaTime;
  2. Hyblademin


    Oct 14, 2013
    Is it that the distance covered during a dodge varies each time it's triggered? I think this is what you are observing, because the force is, of course, set in your script and is constant.

    Physics movement is updated as many times as needed in one loop of the main thread, whether its 0 times, 1 time, or more than 1 time. However, WaitForSeconds yielded routines are checked only once per loop. I think that the number of physics updates executed before 0.05 seconds passes is inconsistent. If that's the case, your character will travel different distances before stopping depending on frame time, which varies.

    You might try making use of WaitForFixedUpdate instead. You can also check for distance travelled to determine when to stop the dash, or otherwise limit the dash length to a maximum distance to get a consistent result.
  3. elgatodorado


    Apr 7, 2019
    WaitForFixedUpdate works but the movement of my dash is much less.

    Moreover, I tried the other method checking the initial distance and final distance but I had the same problem with frames.

    How could I limit the dash length?