How prevent character to jump on mid-air with Physics Matter in Phaser 3?

I have created a jumping functionality for a player in the update() function like so:

if (Phaser.Input.Keyboard.JustDown(this.arrowKeys.up)) {
    //Set ollie power
    ollie = -12;

    //Set skate velocity
    skater.setVelocityY(ollie);

    //Play the ollie animation
    skater.anims.play('ollie');
}

It works well, but the player is able to keep jumping mid-air. I know if I would be using arcade physics I could prevent that like so:

if (cursors.up.isDown && player.body.touching.down)
{
    player.setVelocityY(-330);
}

But with the matter physics won’t work…

I have found a way to check if the player is hitting the floor in the create() function like so:

checkPlayerCollisionWithFloor = () => {
   this.matter.world.on("collisionactive", (skater, ground) => {
      console.log('player hit the floor');
      return true;
   });
}

Now I tried to use this in my update() function like so:

if ( Phaser.Input.Keyboard.JustDown(this.arrowKeys.up) && checkPlayerCollisionWithFloor() ) {
        //Set ollie power
        ollie = -12;

        //Set skate velocity
        skater.setVelocityY(ollie);

        //Play the ollie animation
        skater.anims.play('ollie');
    }

I tried different way to pass the function in if else satement, but it doesn’t work. I need help please.

I have finally found the solution for this issue:

  • First, declare a variable called skaterTouchingGround right after the config object like so:
let skaterTouchingGround;
  • Second, in the create() function add the collision detector event & set the variable skaterTouchingGround to true like so:
//Detect collision with ground
this.matter.world.on("collisionactive", (skater, ground) => {
   skaterTouchingGround = true;
});
  • Third, in the update() function & if statement, add the skaterTouchingGround variable as condition to trigger the jump & once the jump is done set the variable skaterTouchingGround to false like so:
//Ollie
if (Phaser.Input.Keyboard.JustDown(this.arrowKeys.up) && skaterTouchingGround) {
    skaterTouchingGround = false;
    //Set ollie power
    ollie = -12;

    //Set skate velocity
    skater.setVelocityY(ollie);

    //Play the ollie animation
    skater.anims.play('ollie');

}

If you follow these steps, the skater won’t be able to jump midair.

this doesn’t work, don’t use