jorbascrumps

Key just pressed event

Recommended Posts

I'm working on a simple platformer in my spare time with Phaser 3 and I'm currently working on trying to tighten up my controls. Currently I'm trying to prevent jump spamming so that every jump is an intentional action taken by the player. One press of the jump button should translate to only one jump being performed (ie, key must be released to jump again).

Looking at the `Key` class, each key has a property of interest: `_justDown`. This appears to be the property I should use, however it's always `true`. Digging into the source code for v3.1.0 the only time this property is modified is during the process event (`ProcessKeyDown`) and when manually checking using `JustDown`:

function create () {
    this.cursors = this.input.keyboard.createCursorKeys();
}


function update () {
    if (Phaser.Input.Keyboard.JustDown(this.cursors.up)) {
        // Do some jumping
    }
}

This seems to work--sort of--except `ProcessKeyDown` gets called repeatedly and resets the property.. Is there an alternate approach I should be using? I know I could use a jump timer but that seems like a hack. Perhaps this scenario is simply a bug with Phaser at the moment?

Share this post


Link to post
Share on other sites

Instead of justdown I would do something like this with the first statement the beginning of the update loop. It's also easy to expand to support variable height (higher jumps with longer press time):
 

// The player might try to jump if the jump key has been released while standing on the ground
if(!keys.jump.isDown && player.body.blocked.down){
   player.allowedToJump = true;
}
// The jump key is down, the body is on the ground and the player is allowed to jump => jump!
if(keys.jump.isDown && player.body.blocked.down && player.allowedToJump){
   /* Insert jump code */
   player.allowedToJump = false;
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.