Infinite Jumping

Hello!
I have made a simple jumping script but if I press space (spamming it) then I keep jumping up and up and up. How can you fix this problem? Here is the link to editor (Go to act 4) PlayCanvas | HTML5 Game Engine
Here is the script:

var Jumping = pc.createScript('jumping');

// initialize code called once per entity
Jumping.prototype.initialize = function() {
    
};

// update code called every frame
Jumping.prototype.update = function(dt) {
    if(this.app.keyboard.wasPressed(pc.KEY_SPACE) === true){
        this.entity.rigidbody.applyImpulse(0, 5, 0);
    } 
};

// swap method called for script hot-reloading
// inherit your script state here
// Jumping.prototype.swap = function(old) { };

// to learn more about script anatomy, please read:
// http://developer.playcanvas.com/en/user-manual/scripting/

maybe use key up:

this.app.keyboard.on(pc.EVENT_KEYUP, this.onKeyUp, this);

1 Like

Hi @Gabriel_Dobrzynski,

Add a second condition that will allow your player to jump only when he is on the floor.

You can do that in multiple ways, either by checking the player’s pos Y if your game is taking place on a flat surface, or a more complex way is to cast a ray and see if there is a surface underneath the player.

4 Likes

How do i do that

Well a simple way if all of your game is at the same height e.g. 0 is to check that before allowing your player to jump:

var playerPos = this.entity.getPosition();
if( playerPos <= 0){
   // jump
} 

More complex ways involve raycasting, start with the following examples to get familiar with that:

https://developer.playcanvas.com/en/tutorials/?tags=raycast