FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

Game Mechanic: Longer Jumps if Holding Jump Down

In the game Super Mario Brothers. When Mario jumps you can make him jump for longer by holding down the jump button.

This allows for a greater feeling of control and lets you play around with your level design to make for more complex challenges.

Check the Code: what we need to know and do

This mechanic will depend us writing some code to check how long the player has been holding down the jump key and it will change the players velocity based on that value.

Check the Code: what we need to know and do

Our mechanic depend us writing some code to check how long the player has been holding down the jump key and it will change the players velocity based on that value.

To do this we'll need to know about the following game elements;

The code for a minimal example of the Variable Jump Height game mechanic is shown here -  https://mechanic-variable-jump-height.glitch.me/

Going over the code:

Have a look at the code which controls the variable height of the player jump.

    if (game.input.keyboard.isDown(Phaser.Keyboard.UP))  {
        if (player.body.touching.down && jumpTimer === 0) {
            // jump is allowed to start
            jumpTimer = 1;
            player.body.velocity.y = -300;
        } else if (jumpTimer > 0 && jumpTimer < 31) {
            // keep jumping higher
            jumpTimer++;
            player.body.velocity.y = -300 + (jumpTimer * 5);
        }   
    }  
    else {
        // jump button not being pressed, reset jump timer
        jumpTimer = 0;
    }

The code adds an extra if statement into the game which makes a difference between if the player has just touched the jump button or if they are pressing down on the jump button. In the first case the jumpTimer would be at 0 and the code makes the player jump and starts the clock on the jumpTimer variable. The next case where the button is being held down the timer value increases is of importance in the line -- player.body.velocity.y = -300 + (jumpTimer * 5);-- and this increase means that the players velocity is slowed down closer to 0 the longer the button is pressed.

This solution was found at this blog post on amphibian.com which goes into more details about the coding process.

That's it. We hope you enjoy adding this game dynamic to your game to jump on enemies.

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.