Unity3D Input registering for more than one frame?


Keywords:unity3d 


Question: 

I'm designing a platformer in Unity and I implemented a feature where the player:

1) can fall quickly to the ground by pressing down in mid-air

2) cannot jump while holding down

The problem is that the second rule seems to apply for more than one frame--if I tap down, whether in mid-air or grounded, I'm unable to jump for maybe 10 or 20 frames after that. I'm not sure why this would happen since the Update() function is called once per frame.

Here's the Update() code:

 void Update() {
     if((grounded || !doubleJump) && Input.GetButtonDown("Jump") && cannotJump == false) {
         Jump();
     }    

     //Fast Fall
     if (grounded == false) {
         if (Input.GetAxis("Vertical") < 0) {
             rigidbody2D.AddForce(new Vector2(0, -fastFall));
         }
     }

     //Prevent Jump if Fast Fall is held
     if (grounded && (Input.GetAxis("Vertical") < 0)){ 
         cannotJump = true;
     }

     if (grounded && (Input.GetAxis("Vertical") >= 0)) { 
         cannotJump = false;
     }

 }

The game can be played here:

Any help would be appreciated.


2 Answers: 

Instead of doing two separate checks for whether or not you can jump, try assigning it to what you actually want to know. Remove those last two if-branches and try putting this in its place:

cannotJump = Input.GetAxis("Vertical") < 0;

Because the only time you want to disallow jumping is when the player is holding down. The "grounded" check is mostly inconsequential here and I think that's what's actually hurting you.

 

I figured out that the issue had to do with digital axes' gravity. When a button (as opposed to an analogue source like a joystick) is mapped to an axis, gravity determines how quickly the axis snaps back to its neutral (0) position after the button is released.

The default gravity in my setup was 3; the Vertical axis was taking too long to return to 0 even after I released the down button, so the game prevented me from jumping. I fixed the problem by simply changing digital axis gravity to 1000.

Note: this was with the Rewired input manager from the Asset Store, but I think this would apply to Unity's own input manager too.