Kirk Morris
Kirk M. (@saricden)'s blog

Follow

Kirk M. (@saricden)'s blog

Follow
Wrapping Promises in PhaserJS

Photo by Edge2Edge Media on Unsplash

Wrapping Promises in PhaserJS

Useful for managing asynchronous operations in HTML5 game dev

Kirk Morris's photo
Kirk Morris
ยทJan 30, 2022ยท

2 min read

Wrapping Promises in PhaserJS can be a dead useful tool for your game dev arsenal.

One of the major advantages is many function calls in Phaser occur over a set amount of time, and fire events and stuff when they complete.

Nothing wrong with this approach, it's just sometimes being able to chain .then() calls, and use async / await to make asynchronous operations, synchronous, can be very helpful.

Here's a simple example of a function that can be chained and will fire it's .then() or pass a return value into an awaiting variable:

syncYoyoAnim(animKey) {
  this.animationOverride = true;

  return new Promise((resolve) => {
    this.play({
      key: animKey,
      yoyo: true,
      repeat: 0
    });

    this.once('animationcomplete', () => {
      this.animationOverride = false;
      resolve();
    });

  });
}

This function can then be used in situations such as this:

collectFruit(player, fruit) {
  if (!fruit.getData('isCollected')) {
    this.registry.gold++;
    fruit.setData('isCollected', true);
    this.sound.play(`sfx-fruit${fruit.getData('fruit_id')}`);

    this.tweens.add({
      targets: fruit,
      alpha: 0,
      y: fruit.y - 75,
      duration: 300,
      onComplete: () => {
        this.fruits.remove(fruit);
        fruit.destroy();
        player.syncYoyoAnim('death').then(() => {
          // Do other stuff
        });
      }
    });
  }

Let me know in the comments where you find useful little places to introduce Promises into PhaserJS!

PS: I'm working hard on my entry to the thirdweb x Hashnode hackathon. It's coming together super well I'm hyped. Also writing an article describing the development process.

As always, keep coding!

ย 
Share this