[SOLVED] Perform Action For As Long As Key Is Pressed

EDITOR - https://playcanvas.com/editor/scene/909682

Hey everybody,

I am trying to get a car model’s wheels to keep turning left for as long as the left key is pressed. My code is below.

var TurningAnim = pc.createScript('turningAnim');

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

// update code called every frame
TurningAnim.prototype.update = function(dt) {
    this.turn();
};

TurningAnim.prototype.turn = function(dt) {
    if (this.app.keyboard.isPressed(pc.KEY_LEFT) && this.entity.getEulerAngles().y.toFixed(2) < 11.51) {
        this.entity.setEulerAngles(0, 11.51, 0);
    }
    
    else {
        this.entity.setEulerAngles(0, 0, 0);
    }
};

// swap method called for script hot-reloading
// inherit your script state here
// TurningAnim.prototype.swap = function(old) { };

// to learn more about script anatomy, please read:
// http://developer.playcanvas.com/en/user-manual/scripting/

However, the wheels are simply switching very quickly between straight and turned. I have tried putting it in initialize, but it doesn’t work at all then. How can I proceed?

Hi @DevilZ,

You can use the rotate method to do that:

TurningAnim.prototype.turn = function(dt) {
    var rotationSpeed = 1.0;
    if (this.app.keyboard.isPressed(pc.KEY_LEFT) === true) {
        this.entity.rotate(0, rotationSpeed * dt, 0);
    }
};
1 Like

Thanks will try it out.

Hey @Leonidas,

That wasn’t the final fix, but it did help me a lot to finally debug the problem and get there. The problem was having the < 11.51 check inside the main if loop, because that was true only at the end of the rotation. Here is my solution.

TurningAnim.prototype.turn = function(dt) {
    if (this.app.keyboard.isPressed(pc.KEY_LEFT)) {
        if (this.entity.getEulerAngles().y.toFixed(2) < 11.51) {
            this.entity.setEulerAngles(0, 11.51, 0);
        }
    }
    
    else {
        this.entity.setEulerAngles(0, 0, 0);
    }
};

Thanks for your help, it really helped me debug the problem!

1 Like