« Back to Blog

Phaser Platformer Series: 19 One-way Platforms

posted on 19 July 2021

In this tutorial, we’ll add some one-way platforms. Our hero can jump up onto them from below, and they’ll be able to walk on top of them.

Here is what we’ll be making (the one-way platforms are on the far right of the level):

See the Pen
Phaser Platformer Series: 19 One way platforms
by Digitherium (@digitherium)
on CodePen.

If you are viewing on a mobile, you can open a version of it here without all the codepen chrome taking up screen space so you play it in landscape mode.

First, we need to add a new global variable to store our one-way platform sprites group.

oneWayPlatforms,

We’ll be using two different sprites for two different sized platforms. We need to add them to the preload function:

this.load.image('one-way-platform', 'one-way-platform.jpg');
this.load.image('one-way-platform-large', 'one-way-platform-large.jpg');

Next we create the one way platforms group and add our sprites in create:

oneWayPlatforms = this.physics.add.staticGroup();
oneWayPlatforms.create(1400, 352, 'one-way-platform-large');
oneWayPlatforms.create(1400, 320, 'one-way-platform');

As usual, we are just placing the sprites by eye and giving them the correct x and y coordinates. We also need to add our collider between the player and this group:

this.physics.add.collider(player, oneWayPlatforms, null, checkOneWay, this);

Just like our checkLadderTop this collider is using the processCallback instead of the collideCallback. This means it runs before the collison as an extra check, and we can cancel the collision before it happens. We do this in the checkOneWay function:

//called when player collides with oneway platforms
function checkOneWay(player, oneway) {
    //if player is higher up the screen then the plaform then enable the collision
    if (player.y < oneway.y) {
        return true;
    }
    //otherwise disable collision
    return false;
}

If our player is higher than the platform then we enable the physics and the player will be able to walk on the platform. If they are below it they can walk and jump straight through it. Returning true makes the collision go ahead, whilst returning false stops the collision from ever happening. Nice and straightforward. Next up, collapsing platforms.

chromeless mobile version
view all the code on codepen
download the source on github.