How do I reuse a timer after its time has elapsed?

Hello there,

export function create() {

    keys = this.input.keyboard.addKeys('W, S, A, D, Z')

    ///
    timer = this.time.addEvent({
        delay: 500,  
        callback: (()=>{
            console.log("timer has finished!");
            
        })
    });

    timer.paused = true
}

export function update(time, delta) {
    if(keys.Z.isDown) {
        timer.paused = false
    }
    console.log(timer.getElapsed())
}

Im currently fiddling with a timer with the intention of making a melee attack in a third person style, or like in a 2d fighting game ala Street Fighter, Mortal Kombat.

I have a timer set. If I press Z, the timer starts, which will then end at 500. If I log the elapsed time, it will stop at 500 and the log will continue reading the stopped time.
How can I reset the time? So after its pressed, either by the callback?, I somehow trigger the timer to reset, so it can be triggered again. Is that even possible or plausible?

Iā€™m trying to establish a way of making state changes through the use of a timer. For example, I may want a punch or a kick to last 50 milliseconds, where during that time the collision is enabled between two objects (fist and opponent). Once the timer has elapsed, collisions are disabled, you can then press Z again which will start the timer back at 0.

If anyone can explain to me how to do this, or push me in the right direction, I would very much appreciate it.

Thanks.

I would just add a new timer event each time. You could use reset() if you prefer.

var keys, timer;

function onTimerComplete() {
  console.log('timer has finished!');
}

function create() {
  keys = this.input.keyboard.addKeys('W, S, A, D, Z');

  keys.Z.on('down', function () {
    timer = this.time.addEvent({
      callback: onTimerComplete,
      callbackScope: this,
      delay: 500,
    });
  }, this);
}

function update(time, delta) {
  if (timer) {
    console.log(timer.getElapsed());
  }
}
2 Likes