[SOLVED] Play animation?

I am learning playcanvas and javascript and really like it. I have imported a .fbx with animations on them. They load fine. Now what I want is when I press a key i want to play a certain animation. I have taken the “Animation Blending” tutorial but that is focussed on blending between animations and I am looking for playing animations.

It might be a noob question but I can’t seem to find the answer.

It’s the same code. If you don’t want blending then set blendtime to 0 :slight_smile:

1 Like

thanks for the quick response!
The problem I have now is that I have to hold the key pressed to play the animation. If I let go of the key the animation jumps back to idle.

That’s because the code is playing an animation on the key up event (ie when you release a key)

Changing the logic to this:

var AnimationBlending = pc.createScript('animationBlending');

AnimationBlending.states = {
    idle: {
        animation: 'male.json'
    },
    punch: {
        animation: 'male_uppercut_jab.json'
    }
};

// initialize code called once per entity
AnimationBlending.prototype.initialize = function() {
    this.blendTime = 0.0;

    this.setState('idle');
};

AnimationBlending.prototype.update = function(dt) {
    if (this.app.keyboard.wasPressed(pc.KEY_P)) {
        this.setState('punch');
    } else if (this.app.keyboard.wasPressed(pc.KEY_I)) {
        this.setState('idle');
    }
};

AnimationBlending.prototype.setState = function (state) {
    var states = AnimationBlending.states;

    this.state = state;
    // Set the current animation, taking 0.2 seconds to blend from
    // the current animation state to the start of the target animation.
    this.entity.animation.play(states[state].animation, this.blendTime);
};

Allows you to check for key presses in the update loop and change the animation to what you would like it to be.

Tutorial around input: https://developer.playcanvas.com/en/tutorials/keyboard-input/

1 Like

thank you very much! this is what I was looking for.