Phaser Platformer Series: 4 Edge Timer
posted on 22 March 2021
An edge timer is actually something already covered in the official Phaser 2 tutorials. It’s described as ‘a small window of opportunity to still jump, even when you’ve fallen off the side of a platform’. It adds to the game feel, and makes the controls feel much more responsive. This is what we’ll be making:
See the Pen
Phaser Platformer: 4 Edge Timer by Digitherium (@digitherium)
on CodePen.
Two new variables are needed:
wasStanding = false,
edgeTimer = 0;
Then in our update loop we get the current time in milliseconds:
var d = new Date();
var time = d.getTime();
Then we check if we are not standing i.e. we have just technically fallen off a ledge AND we that our new ‘wasStanding’ variable is set to true:
//if we have just left the ground set edge time for 100ms time
if (!standing && wasStanding) {
edgeTimer = time + 100;
}
So this is checking that in this run of the loop we are no longer standing on the floor, BUT in the previous run of the loop we were standing on the floor. This means the edgeTimer only gets set once after leaving a ledge, as opposed to every single time the update loop is called and our hero is falling… if we did that they’d always be able to jump! We set the edgeTimer to be 100ms in the future, that’s going to be our hero’s window to still jump after leaving the ground.
We set our wasStanding flag at the very end of our update loop. So when we hit the loop again, we know what the value of standing was in the previous loop. i.e. we know that we have just fallen off a ledge. This ties in with the previous code to ensure that this window of opportunity only occurs immediately after the hero leaves the ledge:
wasStanding = standing;
Finally all we have to do is change our jump condition to allow a jump if within the window of the edge timer:
if ((standing || time <= edgeTimer) && cursors.up.isDown && !jumping) {
player.setVelocityY(jumpVelocity);
jumping = true;
}
So now if our hero is either standing OR they are in that 100ms window of falling they can jump. That’s still combined with the previous checks, that the up key is down and they aren’t already jumping.
Controls wise, our platformer is starting to shape up. Assuming you have a keyboard that is… would be nice if we had some touch controls for mobile though wouldn’t it? We tackle that next.