[SOLVED] Issue with implementing movement

i’m new to playcanvas and coding in general and i’m trying to add basic movement but it gives me the error “uncaught typeerrror: cannot read properties of undefined(reading keyboard)” i have looked through the code many times and cannot seem to find the problem

this is the code

var Movement = pc.createScript('movement');

Movement.attributes.add('speed', {type: 'number'});
Movement.attributes.add("jump", {type : "number"});

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

// update code called every frame
Movement.prototype.update = function(dt) {
    
    
    // calculate force based on pressed keys
    if (this.app.keyboard.isPressed(pc.KEY_LEFT)) {
         this.entity.rigidbody.applyForce(
         -this.speed,
         0,
         0
         );   
    } 

   if (this.app.keyboard.isPressed(pc.KEY_RIGHT)) {
         this.entity.rigidbody.applyForce(
         this.speed,
         0,
         0
         );       
    }

    if (this.app.keyboard.isPressed(pc.KEY_UP)) {
         this.entity.rigidbody.applyForce(
         0,
         0,
         this,speed
         ); 
    } 
    
    if (this.app.keyboard.isPressed(pc.KEY_DOWN)) {
         this.entity.rigidbody.applyForce(
         0,
         0,
         -this.speed
         ); 
}
    
};
    
    if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
         this.entity.rigidbody.applyForce(
         0,
         this.jump,
         0
         );
       {
    }

}

Hi @Stary_Fallstar and welcome! That’s probably because you close the function with }; right before your spacebar statement. Because of that, the spacebar statement is outside the function and the script can’t read that correctly. After your spacebar statement there is also a wrong {. In the script below I have fixed these mistakes for you.

var Movement = pc.createScript('movement');

Movement.attributes.add('speed', {type: 'number'});
Movement.attributes.add("jump", {type : "number"});

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

// update code called every frame
Movement.prototype.update = function(dt) {
 
    // calculate force based on pressed keys
    if (this.app.keyboard.isPressed(pc.KEY_LEFT)) {
         this.entity.rigidbody.applyForce(-this.speed, 0, 0);   
    } 

    if (this.app.keyboard.isPressed(pc.KEY_RIGHT)) {
         this.entity.rigidbody.applyForce(this.speed, 0, 0);       
    }

    if (this.app.keyboard.isPressed(pc.KEY_UP)) {
         this.entity.rigidbody.applyForce(0, 0, this,speed); 
    } 
    
    if (this.app.keyboard.isPressed(pc.KEY_DOWN)) {
         this.entity.rigidbody.applyForce(0, 0,-this.speed); 
    }

    if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
         this.entity.rigidbody.applyForce(0, this.jump, 0);
    }
};
2 Likes

thank you i appreciate your help

1 Like