Search code examples
javascriptphaser-frameworkphaserjs

Jump trough (up and down) platform in Phaser 3


I followed this tutorial which works great for jumpin up and landing on top of the platform.

I've setup the collision disable trick (so players can also jump down through) which also works great.

My issue is: This applies to ALL the Tiled layers.

How can you check if the tiles the character is standing on is actually from a specific layer from your Tiled map?

My current setup:

// Import map from Tiled
this.map = this.make.tilemap({ key: 'myBeautifulMap' });
this.platform = this.map.createLayer('platform', this.tileset);

// Apply collision to ALL tiles from this Layer
this.platform.setCollisionByExclusion(-1, true); 

// disable one side collision so character can jump up trough it
this.platform.forEachTile(tile => {
  if (tile.index > 0){
    tile.setCollision(false, false, true, false);
  }
});

// Allow jump down
// This part shoudl check if the tiles the character is standing on are part of the 'platform' Layer
if (this.keyboard.S.isDown) {
  this.body.checkCollision.down = false;
  this.scene.time.addEvent({ 
    delay: 400,
    callback:  () => {
      this.body.checkCollision.down = true;
    },
    callbackScope: this 
  }); 
}

Solution

  • Well one easy solution would be to add a collider event in the create function for each layer.

    per Layer one line of code like this:

    this.physics.add.collider(player, layer, (p, t) => this.playerOnTileLayer = t.layer);
    

    now when the player lands on a tile, the variable will be set. Now you could check if the player is on that specific layer.

    Something like this:

    if (this.keyboard.S.isDown && this.playerOnTileLayer == this.platform) {
       ...
    }
    

    If the player can land on other GameObjects, that aren't tiles, you could reset the variable (this.playerOnTileLayer = null;) on keypress, or on each collision with non tiles. Just to be on the save side, that the variable is always set correct.