Problem with my DoubleJump script

Hello everybody!

I’m new at scripting in Unity, so I’m trying to make a simple player movement to improve my skills. Im using javascript. I have done the basic movement and a simple jump, but I’m trying to do a double jump with this script:

(I’ve put some explanations as comments to do the question easier)


	if (controller.isGrounded) {  //If the player is on the floor
	contadorsalto = 0; 			//Reset the counter
	moveDirection.y = 0;
	if (Input.GetButton ("Jump")) {  //When press space
		moveDirection.y = jumpSpeed;  //Jump
		contadorsalto = 1; 			//Counter = 1
	}
} else {							//If the player is NOT on the floor
	if (contadorsalto < 2) {		// and the counter is less than 2 (only 1 jump)
		if (Input.GetButton ("Jump")){  //When we press space
			moveDirection.y = jumpSpeed;  //Jump
			contadorsalto = 2;				//Counter = 2 so it won't enter again until player is in the floor 
		}
	}
}

moveDirection.y -= gravity * Time.deltaTime;

controller.Move(moveDirection * Time.deltaTime);

Do you have any Idea why I can only jump once?

Thanks a lot!
Greetings

1 Answer

1

The GetButton() function returns true every frame when the button in question is pressed. Since no one is quick enough to press a button for exactly one frame, the function almost always returns true for several frames in a row. This behaviour is desired in some cases.

However, in your case, it means your counter is increased to 1, and then, on the next frame, it gets increased to 2 because you haven’t released the button yet. The y-axis movement speed gets updated twice in a row, before you can notice the influence of gravity.

Long story short: use GetButtonDown() instead. It only returns true on the frame when the button was pressed. In order to perfom a double jump, you will need to release the button and press it again, which I guess is exactly how you want the game to behave.