Character controller on Input

Hey guys,

I am currently working on a 2d project which involve a character that the user is controlling. For now the only way I found to control this character is using the update function in a script waiting for inputs and updating the character position (see below).

I have been looking at different script for controlling characters and always found this way of doing things. However, I am not really satisfied with it because it means that when the user is not giving any input the function update is still running. Is there a way to update the position of my character only on user’s inputs? Maybe by mixing the event EVENT_KEYDOWN and isPressed(key) however I would need to have the delta time that the function update has. Hopefully we can find a way to improve this script!

Thank you for your help

Hi @Ougogogadget,

That’s good thinking. You can use keyboard events as shown in this tutorial:
https://developer.playcanvas.com/en/tutorials/keyboard-input/

Now when a key is down, don’t move the character directly in your input handler, just set a script wide property to true. Example:

KeyboardHandler.prototype.initialize = function() {

    this.input = {
        left: false,
        right: false
    };

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

// update code called every frame
KeyboardHandler.prototype.update = function(dt) {

    if(this.input.left){
        // do things
    }
};

KeyboardHandler.prototype.onKeyDown = function (event) {

    if (event.key === pc.KEY_LEFT) this.input.left = true;
    if (event.key === pc.KEY_RIGHT) this.input.right = true;
};

KeyboardHandler.prototype.onKeyUp = function (event) {
    if (event.key === pc.KEY_LEFT) this.input.left = false;
    if (event.key === pc.KEY_RIGHT) this.input.right = false;
};

You can now use the input in your update loop together with the delta time. That way you can also use the same object with other types of input e.g. mouse or gamepad.

It works, thank you!