[help] delay in coding


#1

I’m trying to have a sprite play a specific animation just before moving, but setTimeout() doesn’t seem to work

// this.ani is the type of animation
 if(this.app.keyboard.wasPressed(pc.KEY_RIGHT)){
        this.ani=1;
       //insert delay here
        this.ani=2;
    }

#2

I’m pretty new to this stuff, so this may not be the best answer, but I’m pretty sure it will work

// this.ani is the type of animation
 if(this.app.keyboard.wasPressed(pc.KEY_RIGHT)){
        this.ani=1;
        this.ani2_toggle = true;
        this.ani2_timer = 0; // make sure that our timer is set to 0
        this.ani2_delay = 5; //set this to whatever number of seconds you want
       //this.ani=2; //Leaving this for reference.  Will execute this statement in the update function
    }

someScriptName.prototype.update = function(dt){ 
    if (this.ani2_toggle === true && this.ani2_timer <  this.ani2_delay ){
        this.ani2_timer += dt; //increment the timer
        }
    if (this.ani2_toggle === true && this.ani2_timer >= this.ani2_delay) {
        this.ani = 2; // We execute this now that the timer has run for the length of the delay
        this.ani2_toggle = false; //reset our toggle to stop either of these two if conditions from executing
        this.ani2_timer = 0; // Let's go ahead and reset the timer to 0 as well though this isn't strictly necessary
        }
}