Jump to content

onkeyup event (onUp)


jd.joshuadavison
 Share

Recommended Posts

Hi,

Broad question

It's my second day learning Phaser. I've dived straight into Phaser 3, but its proving challenging since the docs are only available in the GitHub repo. It looks like there was an event handler in Phaser 2 called 'onUp' which would only fire once when a key was released instead of continuously firing for as long as the key is held down like 'isDown' does. This doesn't seem to exist in Phaser 3 - what is the correct way of doing this in Phaser 3?

In this particular instance I'm trying to do this on a cursor key, but it would be useful to know how to do it on any key if it's different.

Specific scenario

I've enabled my player sprite to 'double jump' using the following code in the update function.

if (cursors.up.isUp) {
    jumpReleased = true;
}
if (cursors.up.isDown && player.body.onFloor()) {
    player.body.setVelocityY(-300);
    player.anims.play('idle', true);
    jumpCount = 1;
    jumpReleased = false;
    jumpTime = new Date().getTime();
} else if (cursors.up.isDown && jumpReleased === true && jumpCount === 1 && ((new Date().getTime() - jumpTime) < 1500)) {
    player.body.setVelocityY(-400);
    player.anims.play('idle', true);
    jumpCount = 2;
    jumpReleased = false;
}

`isDown` simply fires if the key is being pressed at the time that the update function fires, which is a lot. I was hoping to find a way to simply fire this event on key up (like the native javascript event handler) - this way I wouldn't have to set and check `jumpReleased`. Is there a way to do this? More to the point, is there a correct way to do this?

Thanks,
Josh

Link to comment
Share on other sites

Thanks Doug! I really wish I'd found the labs earlier! That's exactly what I'm looking for.

In fact, Phasers keydown event works differently from the regular javascript onkeydown. Javascript's onkeydown will keep firing repeatedly if you hold the key down, Phasers keydown only fires once, so I think I prefer keydown to keyup!

Here's my new event listener in the create function.

this.input.keyboard.on('keydown_UP', function (event) {
    if (player.body.onFloor()) {
        player.body.setVelocityY(-400);
        player.anims.play('idle', true);
        jumpCount = 1;
        jumpTime = new Date().getTime();
    } else if (jumpCount === 1 && ((new Date().getTime() - jumpTime) < 1500)) {
        player.body.setVelocityY(-300);
        player.anims.play('idle', true);
        jumpCount = 0;
    }
});

This certainly feels more right than what I'd written in the update function.

Thanks,
Josh

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...