Playing animation via code

Hi. I’m trying to play an animation via code. Goal is to have it play, than wait for a random amount of seconds (within a range) until it fires again. I’ve been messing with a combination of a super simple state graph + Anim component + some code but just can’t get it to even fire at will via keyup event. This ought to be really simple no?

Hi @bjorn.syse,

Have you check the following tutorial? It shows exactly that, how to fire an animation transition on keydown:

https://developer.playcanvas.com/en/tutorials/anim-blending/

There’s also this which could be simpler to do depending on your use case: Animation without State Graph | Learn PlayCanvas

1 Like

Hi, no but problem is I only have one animation clip. I have one state, and I want to repeat that. Not blend into anything else. I want to run animation once at start. Then after that be able to run it again.

This is my state graph:

And I just it working by calling Anim.reset(). Is that bad practice?

var AnimationRandomizer = pc.createScript('animationRandomizer');

// initialize code called once per entity
AnimationRandomizer.prototype.initialize = function() {
    
this.anim_component = this.entity.anim;
  
    this.app.keyboard.on(pc.EVENT_KEYUP, this.onKeyUp, this);
};

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

};

AnimationRandomizer.prototype.startAnimation = function() {

        this.anim_component.reset();   
};

/*
* Event handler called when key is pressed. Dev mode only. 
*/
AnimationRandomizer.prototype.onKeyUp = function (event) {
    
    console.log("Key up in " + this.entity.name);

    if (event.key === pc.KEY_NUMPAD_5) {
      
        this.startAnimation();
      
    }

};

I don’t think that blends animation when called. You would likely be better off using the transition method shown the tutorial that I linked earlier.