this.entity.translateLocal(0,-0.1,0); is undefined

for some reason when i put this.entity.translateLocal(0,-0.1,0); in a function like:
function movement() {
this.entity.translateLocal(0,-0.1,0);
}
i get the error message: cannot read translatelocal of undefined.
it seems that a function cant read translatelocal. if you have a solution plz tell me.

Hi @vilothaine_2,

Your script method should be structured like this, to have access to the right this context that includes useful properties like app, entity etc.:

MyScript.prototype.movement = function() {
   this.entity.translateLocal(0,-0.1,0);
}

Study the manual section on scripting to learn more on this:

https://developer.playcanvas.com/en/user-manual/scripting/

1 Like

i got it

also, how can i trigger a function with keyboard input

MyScript.prototype.update = function(dt) {
    if (this.app.keyboard.isPressed(pc.KEY_W)) {
        this.movement();
    }
};

2 Likes

is there a way i can make the function only work once? also can i make it repeat?

If you start a function inside the update function, it will be repeated continuously. In the example above, this only happens when the W key is pressed. You can add other conditions to the if statement to ensure that the function is only started when you want. Another option is to start the function not inside the update function.