2d Platformer double jump wont work
Hi guys, Im trying to set up the double jump code for my 2d platformer but it doesnt seem to work.
if (Input.GetKey(KeyCode.Space) && onGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpheight);
canDoubleJump = true;
}
if (Input.GetKey(KeyCode.Space) && canDoubleJump && !onGround)
{
rb.velocity = new Vector2(rb.velocity.x, jumpheight);
canDoubleJump = false;
}
So first im checking if im on the ground so I cant jump forever then setting canDoubleJump bool to true, so the next time I press the jump key while im not on the ground I can jump again. But the problem is as soon as I jump the canDoubleJump bool goes true then instantly false so I can only jump once. Any help? I also tried this code from a youtube video but it has the same effect:
if (Input.GetKey(KeyCode.Space))
{
if (onGround) {
rb.velocity = new Vector2(rb.velocity.x,jumpheight);
canDoubleJump = true;
}
else
{
if (canDoubleJump)
{
//rb.velocity = new Vector2(rb.velocity.x, 0);
rb.velocity = new Vector2(rb.velocity.x, jumpheight);
//rb.AddForce(Vector2.up * jumpheight);
canDoubleJump = false;
}
}
}
Answer by Commoble · Apr 20, 2017 at 05:25 PM
The fundamental problem here is that Input.GetKey doesn't "clear" the keypress; if the key is being held during that frame, it returns true. However, since framerates tend to be much faster than human fingers, a single press of the spacebar will hold it down for many frames.
With this in mind, both blocks of code don't appear to work for the same reason: When the user presses the spacebar, the player object will start jumping. In the next frame, the player object will have left the ground, but the user will still be holding the spacebar, so the double-jump code triggers immediately.
A simple way to fix this is to use Input.GetKeyDown()
instead of Input.GetKey()
. GetKeyDown only returns true on the very first frame of the keypress; it will return false in subsequent frames until the user releases the key and presses it again.
I also suggest using your second code block with this; the code is cleaner and will cause fewer additional problems down the line.