Search code examples
javascriptgame-enginegame-physicsbounding-boxphaser-framework

How to enable jumping "just before" the player touches the ground in Phaser?


With Phaser (and following allong with the tutorials) jumping is super-easy with the provided Arcade physics module. However, it has the annoying-to-me fact that a player can only jump when they are "on" the ground due to the use of player-is-touching-down logic.

The code I am using is based on Game Mechanic Explorer, Platformer #4 and follows;

var canJump = this.player.body.touching.down;

if (canJump && this.upInputIsActive()) {
    this.player.body.velocity.y = this.JUMP_SPEED;
}

I would like to enable a player be able to jump when they are really close to the ground but are not yet touching so that the re-jump/jump-as-landing is more fluid. As such, and the observation that the limit is caused by touching.down of the player, my questions are;

  1. Is it possible to determine the distance ("how high") the player is from the ground (which can be a platform) immediately below them? Then canJump is just a function of the distance, being true for very small values only.

  2. Can a virtual hit-box be extended around the player (that would travel-with the player) such that it's own touching.down could be used to detect this case? Is this approach better? The player sprite itself should not levitate off the ground or otherwise be effected.

The goal here is specifically to allow the player to jump just before they ought to be able to - so remembering an up key-press for a short duration of time, which may be viable, is not a solution I am seeking in this particular case.


Solution

    1. Not "natively". There is no CCD or look-ahead, a body is only concerned with the direction it is travelling. What you're trying to achieve is commonly known as using a sensor. P2 has support for sensors, but Arcade Physics doesn't, so you'd have to simulate it - either by creating a second body (which you've alluded to in point 2) or using a marker. This could be a simple Point object that is 'dropped' when they jump and you can then use the built in distance checks between the point and the body to allow for your 'near jump' requirement.

    2. Yes it can, but your Sprite will then 'float' in the air. So see point 1 :)