How to make your character keep jumping while key is pressed

I want to make sure that the duration of pressing key decides the height of jump and once key is released, it immediately falls.
In the following code, it sometimes works and in other cases, the jump keeps going on even without the key pressed anymore!
Could you tell me a good solution?

if(isGrounded && ( Input.GetKey(KeyCode.Joystick1Button3)) {

 rigidbody.velocity = Vector3.up * JumpSpeed;

}
else if(Input.GetKeyUp(KeyCode.Joystick1Button3)){
rigidbody.velocity = Vector3.down * GravitySpeed ;
}

1 Answer

1

If you want to have duration, then you should hold a timer like this:

if( isGrounded && Input.GetButton("Jump")){
  isJumping = true;
  jumpDuration += Time.deltaTime;
}

and in another part

if( isJumping && jumpDuration > 0){
  here goes jumping;
  jumpDuration -= Time.deltaTime;
}