How do i make my character jump only when its on the ground

I was just messing around im my thing with my brother testing my jump and i can just jump without being on the ground how do i stop that?

here is a link PlayCanvas | HTML5 Game Engine

I can’t explain correctly since I’m on mobile now, but it requires you to check the ground using a predefined event. I think it’s called onCollisionStart.

First, add a tag that says ground to the ground entities in your game.

Then:

//Variables
var onGround = false;
var jumpForce = 4; // Change to whatever you want

FirstPersonMovement.prototype.initialize = function() {
    // Define Events
    this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown, this);
    this.app.keyboard.on(pc.EVENT_KEYUP, this.onKeyUp, this);
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
};

FirstPersonMovement.prototype.update = function(dt) {
    // Jump
    if (this.app.keyboard.wasPressed(pc.KEY_SPACE) && onGround === true) {
        this.entity.rigidbody.applyImpulse(0, jumpForce, 0); // Apply Impulse
        onGround = false; // Set onGround variable to false
    }
};

FirstPersonMovement.prototype.onCollisionStart = function(result) {
    // Ground Check
    if (result.other.tags.has('ground')) {
        onGround = true;
    }    
};
  1. Trigger on char bottom
  2. Check trigger on ground collision
  3. Set counter for simultaneously ground collision (+1 in start collision, -1 if end collision)
1 Like

Edit for correct check. Without counter will bug on change ground entity

I’ve never had much of a problem with this way of checking ground entities.

But maybe you can give an example of wat the ideal jump limit script would look like.

Simply:
Two closest ground entities, walk from one to second, isGrounded=true (because on ground), move to second, trigger again, leave from first (isGrounded=false), but second ground entity is… none ))

If using counter, we have 1, between entites have 2, leave first - have 1. Counter == 0 if no ground

Not sure if I understand. But what the script does is it sets the onGround variable to false when you jump. If you add the ground tag to all ground entities, you shouldn’t have much of a problem jumping to different grounds. One problem with using this method from what I know off, is that if you just walk of a platform, you’re able to jump once mid air.

Look at example with moving from 1 to 3
In collide after two grounds we have bug after leave one of ground - flag set to false, but on ground

this.groundCounter = 0;
this.entity.collision.on('triggerenter', ()=> { this.groundCounter++; }, this);
this.entity.collision.on('triggerleave', ()=> { this.groundCounter--; }, this);
this.isGrounded = ()=>{ return this.groundCounter>0; };