Ch012 - Game Mechanic: Longer Jumps if Holding Jump Down

Ch012 - Game Mechanic: Longer Jumps if Holding Jump Down

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.

What we need to know and do

Our mechanic depends 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 it’s helpful to know about the following game elements;

Going over the code:

The code for a minimal example of the Variable Jump Height game mechanic is shown here - https://jamm-labs.github.io/ggcp/mechanic-variable-jump-height/game.js

In the global variable area at the start of the code see that there is a variable declared there called jumpTimer.

var jumpTimer = 0;

In the Playstate.update function, we add 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.