Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

RigidBody2D.AddForce and Coroutine with WaitForSeconds

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

  1. elgatodorado

    elgatodorado

    Joined:
    Apr 7, 2019
    Posts:
    22
    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)
    2.  
    3. if (Input.GetKeyDown("s") && suelo && !esquivando && cooldown<=0)
    4.         {
    5.             esquivando = true;
    6.             myBody.velocity = Vector2.zero;
    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.         }
    17.  
    18. //Coroutine
    19.  
    20. IEnumerator Dash()
    21.     {
    22.         yield return new WaitForSeconds(0.05f);
    23.         myBody.velocity = Vector2.zero;
    24.         esquivando = false;
    25.         cooldown = 0.5f;
    26.     }
    Moreover, i have a cooldown:

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

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    723
    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

    elgatodorado

    Joined:
    Apr 7, 2019
    Posts:
    22
    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?