[SOLVED] What is wrong in this code?

I tried this code in this isn’t working in the game?

var Jump = pc.createScript('jump');

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

Jump.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);
};

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

Jump.prototype.onCollisionStart = function(result) {
    // Ground Check
    if (result.other.tags.has('ground')) {
        onGround = true;
    }    
};

Hi @MATURE!

What is the current result?

Has your ground entity a ground tag?

no

i added but didnt work

What is the current result?

Alternatively, you can try the script from my example project below.

https://playcanvas.com/project/1063800/overview/basic-jumping

it didn’t say any error but when i press space the player wont jump

its working now from that project thanks

I would set onGround to true by default, but I don’t know if this is the cause of the problem.

Great! :+1:

no wait when i applyed that code the player is jumping but when i press space in air i will start jumping again

There is a sensor length attribute. You have to decrease this value.

2 Likes