Home > Enterprise >  Unity Addforce Bug
Unity Addforce Bug

Time:12-19

I'm currently working on a simple 2d jump and run game. I want to move my player with physics (using addforce).

  1. In the editor, my player jumps at a normal height. But when i build the game it suddenly jumps way higher. I put everything in fixedUpdate() and don't know where the problem is?

     //Movement
     rb.velocity = new Vector2(horizontalMove, rb.velocity.y);
     //Jump
     if (jumpPressed)
     {
         if (isGrounded)
         {
             rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
             anim.SetTrigger("takeOf");
         }
     }
    

Dan

CodePudding user response:

If jumpPressed is true for every frame when the jump key is held, this could be the issue. This would mean that the code could act several times, reapplying the upwards force several times (before it goes far away enough from the ground that the ground check does not detect it). If this is the case, it can be fixed by:

  • rather than using AddForce, set the vertical velocity to the velocity of the jump.
  • changing the jumpPressed to only return true if jump was pressed this frame
  • Imposing a limit to how often you can jump (if you cannot jump twice within 0.1 seconds, that could fix the issue)
  • Related