Pobtastic / Goldfish Game / Air

Created Mon, 22 Apr 2024 13:34:27 +0100 Modified Sat, 04 May 2024 21:31:28 +0000

Introduction

As with all the images, preload first:

  preload() {
    // Preload the air asset.
    this.load.image('air', '/images/booty/air.png');
  }

Let’s create a variable to hold the oxygen bar sprites:

  class MainScene extends BaseScene {
    constructor() {
      super('MainScene');
      this.oxygenSprites = [];
    }
  }

Here we’ll set the initial value of the air bar, and populate our air bar graphics. The idea with this is that each value in the array will correspond with a section of the air bar, and we’re just going to set them to be visible/ invisible according to the length variable.

A Phaser event timer will handle decreasing the oxygen value.

  create() {
    // Initial value for length of air bar.
    this.data.set('oxygenLevel', 19);

    // Add repeated air bar graphic to the oxygen sprites array.
    for (let i = 0; i < this.data.get('oxygenLevel'); i++) {
      let airSprite = this.add.image((12 + i) * 8 * this.gameScale, 8 * 22 * this.gameScale, 'air').setOrigin(0, 0);
      airSprite.setVisible(true);
      this.oxygenSprites.push(airSprite);
    }

    // Start the timer event for decreasing oxygen.
    this.time.addEvent({
      delay: 3000,
      callback: this.decreaseOxygenLevel,
      callbackScope: this,
      loop: true
    });
  }

This is the event timer callback we declared in the create() method:

  decreaseOxygenLevel() {
    // Ensure the oxygen level is always zero or higher.
    let newLevel = Math.max(this.data.get('oxygenLevel') - 1, 0);

    // Update the stored value.
    this.data.set('oxygenLevel', newLevel);

    // Draw/ update the air bar.
    this.updateOxygenDisplay();
  }

This doesn’t really need to be a separate method, I just feel it’s a bit neater being on its own here… All we’re going to do, is set/ unset the visibility for each sprite in the oxygen array according to the current this.data.oxygenLevel variable:

  updateOxygenDisplay() {
    this.oxygenSprites.forEach((sprite, index) => {
      sprite.setVisible(index < this.data.get('oxygenLevel'));
    });
  }

This is how it looks. We’ll add the player interactions with it later.

Booty Disassembly