30May/110
Double Jump in PSK
Double jumping is pretty common in most platformers so I thought I'd share some code I use for it.
Here's a video showing the final product:
In Player.cs add the following underneath the other jumping code. (MaxJumpTime, JumpControlPower, etc.)
1 | private int numberOfJumps = 0; |
Now find this line in Update(...)
1 | isJumping = false; |
and add this after it:
1 2 | if (isOnGround) numberOfJumps = 0; |
Now in the DoJump(...) method find this block of code
1 2 3 4 5 6 7 8 9 10 11 12 13 | // If we are in the ascent of the jump if (0.0f < jumpTime && jumpTime <= MaxJumpTime) { // Fully override the vertical velocity with a power curve that //gives players more control over the top of the jump velocityY = JumpLaunchVelocity * (1.0f - (float)Math.Pow(jumpTime / MaxJumpTime, JumpControlPower)); } else { // Reached the apex of the jump jumpTime = 0.0f; } |
and change it to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // If we are in the ascent of the jump if (0.0f < jumpTime && jumpTime <= MaxJumpTime) { // Fully override the vertical velocity with a power curve that //gives players more control over the top of the jump velocityY = JumpLaunchVelocity * (1.0f - (float)Math.Pow(jumpTime / MaxJumpTime, JumpControlPower)); } else { // Reached the apex of the jump and has double jumps if (velocityY > -MaxFallSpeed * 0.5f && !wasJumping && numberOfJumps < 1) { velocityY = JumpLaunchVelocity * (0.5f - (float)Math.Pow(jumpTime / MaxJumpTime, JumpControlPower)); jumpTime += (float)gameTime.ElapsedGameTime.TotalSeconds; numberOfJumps++; } else { jumpTime = 0.0f; } } |
And that's it! You're able to double jump slightly after the first jump and whenever you're on the ground your jump count gets reset so you're able to double jump again.