Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Bug Problems with AddForce

Discussion in 'Physics' started by andreramosvieira, Feb 4, 2024.

  1. andreramosvieira

    andreramosvieira

    Joined:
    Jun 7, 2022
    Posts:
    5
    So I have been working on this 2D project that's my first game ever. I have a player and I have been trying to make a dash for it but I cant get AddForce to work in the player object and I also can't find other ways of doing it that doesn't deppend on fps. Where is the dash code and the player's settings.
    Notes: The problem is really with the AddForce because if I instead I use the commented code it works, but that way deppends on the frames per second so I wanted to change it.

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.LeftShift) && canDash && !onWall())
    2. {
    3.     body.velocity = new Vector2(0, body.velocity.y);
    4.     StartCoroutine(Dash());
    5. }
    6.  
    7. private IEnumerator Dash()
    8. {
    9.     canDash = false;
    10.     isDashing = true;
    11.     float originalGravity = body.gravityScale;
    12.     body.gravityScale = 0f;
    13.     body.velocity = new Vector2(0, 0);
    14.     anim.SetTrigger("dash");
    15.  
    16.    
    17.     playerHealth.isInvulnerable = true;
    18.     Physics2D.IgnoreLayerCollision(9, 7, true);
    19.  
    20.  
    21.     //float startTime = Time.time;
    22.     //while (Time.time < startTime + dashingTime)
    23.     //{
    24.  
    25.     //    Vector2 pos = body.position;
    26.     //    if (transform.localScale.x > 0f)
    27.     //        pos += new Vector2(1 * dashingPower, 0.0f);
    28.     //    else
    29.     //        pos += new Vector2(-1 * dashingPower, 0.0f);
    30.  
    31.     //    body.MovePosition(pos);
    32.  
    33.     //    yield return null;
    34.     //}
    35.     Vector2 distance = new Vector2(dashingPower, 0);
    36.     distance = distance.normalized;
    37.     body.AddForce(distance, ForceMode2D.Impulse);
    38.     Physics2D.IgnoreLayerCollision(9, 7, false);
    39.     playerHealth.isInvulnerable = false;
    40.  
    41.  
    42.  
    43.  
    44.     body.gravityScale = originalGravity;
    45.     isDashing = false;
    46.     yield return new WaitForSeconds(dashingCooldown);
    47.     canDash = true;
    48.  
    49. }
    upload_2024-2-4_0-13-52.png
    upload_2024-2-4_0-14-22.png
     
  2. Gabo_campitelli

    Gabo_campitelli

    Joined:
    Oct 17, 2012
    Posts:
    426
    First of all you are making very wrong use of a coroutine. you are just going trough the code once.
    you commented code implement iteration but at least instead of
    Code (CSharp):
    1. yield return null;
    use
    Code (CSharp):
    1. yield return New WaitForSeconds(Time.fixedDeltaTime);
    but better just use FixedUpdate()
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html