1
\$\begingroup\$

In a platformer game I am working on, I want my character to have controlled jumps. If I simply tap the jump key it will jump a just a little or if I hold it for a time it will jump higher.

What do I need to do?

\$\endgroup\$
  • 1
    \$\begingroup\$ Do you already have the maths for your jump physics? I'd say to enable a jump state when the jump key is pressed and stop it when it's released. But it all depends on how you simulate your jump. \$\endgroup\$ – Grybouilli Apr 13 at 11:18
  • 1
    \$\begingroup\$ Have you reviewed existing tutorials, Q&As and guides about this topic? (These are all from the first few Google results) What have you tried based on your research so far? \$\endgroup\$ – DMGregory Apr 13 at 11:40
4
\$\begingroup\$

You have essentially 2 options. You can either apply a constantly decreasing force to the character while the player is pressing the space button and stop immediately when they release it or apply a higher force of gravity when the player releases the space and go back to normal gravity, when the jump reaches the peak. For instance, the first Super Mario Bros used the latter.

The first option is in my opinion a lot more intuitive and gives you a nicer curve, but the latter can be a little more responsive and gives you better control over the jump height.

The former is also harder to get right in a game design perspective, since instead of defining a max jump height, you only set the minimum.

Implementing both is fairly easy, for the first one you'll need to store the current jump force somewhere. Pseudo code

jumpForce = 10
jumpDampening = 0.8 // This determines how much the jump force weakens every frame.

// Later
if (jumpKeyDown) {
    player.velocityY += jumpForce
    jumpForce *= jumpDampening
} else {
    jumpForce = 10
}

// Apply gravity

The other one needs to detect when the jump reaches it's peak too:

normalGravity = -9.81
stoppingGravity = -30
jumpForce = 30

// Later
if (playerIsOnGround && jumpKeyDown) {
    player.velocityY += jumpForce
}

// Apply gravity based on whether the jump reached it's peak yet
if (!jumpKeyDown && player.velocityY > 0) {
    player.velocityY += stoppingGravity
} else {
    player.velocityY += normalGravity
}

Side note:

If you want to get a "tighter" jump, then always apply the stronger gravity when the player isn't holding the jump button. This will let the character fall to the ground faster, resulting in more control.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.