Pobtastic / Phaser Guide / Scene

Created Thu, 13 Feb 2025 21:58:09 +0100 Modified Thu, 20 Feb 2025 15:27:57 +0000

Introduction

This is a whole lot easier now I have some “learnings” from making the Booty Goldfish Game.

Build The Scene

All the set-up is identical to Building The Scene from the Goldfish Game, I’m simply loading the West Bank assets instead and painting the canvas a different colour.

constructor() {
  super();
  // Set the starting number of player lives.
  this.lives = 3;
  // Holds the bandits.
  this.bandits = [];
  // Simply because I've made the assets use scale 4 in the disassembly.
  this.gameScale = 4;
}
preload() {
  // Preload the bandit assets.
  for (let i = 1; i <= 3; i++) {
    // There are four frames for each bandit.
    for (let f = 1; f <= 4; f++) {
      this.load.image(`bandit-${i}-${f}`, `/images/westbank/bandit-${i}-${f}.png`);
    }
  }
  // Preload the score/ lives assets.
  const uiElements = ['score-text', 'lives-text', 'lives'];
  uiElements.forEach(element => {
    this.load.image(element, `/images/westbank/${element}.png`);
  });
}
create() {
  // Add the "sky".
  this.add.rectangle(0, 3 * 8 * this.gameScale, config.width, 8 * 12 * this.gameScale, 0x00C6C5).setOrigin(0, 0);
  // Add the "grass".
  this.add.rectangle(0, 15 * 8 * this.gameScale, config.width, 8 * 4 * this.gameScale, 0x00C600).setOrigin(0, 0);
  // Add the "footer" images.
  this.add.image(8 * 1 * this.gameScale, config.height - 8 * 3 * this.gameScale, 'score-text').setOrigin(0, 0);
  // The "off-by-one" here is due to (oddly) one of the assets has some blank space above the lettering.
  this.add.image(8 * 17 * this.gameScale, config.height - 8 * 4 * this.gameScale, 'lives-text').setOrigin(0, 0);
  // Cycle through the remaining lives and print an icon for each one in the footer.
  for (let i = 1; i <= this.lives; i++) {
    this.add.image(8 * (21 + i * 2) * this.gameScale, config.height - 8 * 4 * this.gameScale, 'lives').setOrigin(0, 0);
  }
  // Create the bandit sprites.
  for (let i = 1; i <= 3; i++) {
    const bandit = this.add.sprite(
      8 * ((i * 9) - 2) * this.gameScale,
      8 * 12 * this.gameScale,
      `bandit-${i}-1`
    );
    // Add the frames.
    bandit.frameNames = [
      `bandit-${i}-1`,
      `bandit-${i}-2`,
      `bandit-${i}-3`,
      `bandit-${i}-4`
    ];
    // Add to the bandits array.
    this.bandits.push(bandit);
  }

  // Let's just play the animation over and over for now.
  this.bandits.forEach((bandit, index) => {
    this.anims.create({
      key: `bandit-${index + 1}-anim`,
      frames: bandit.frameNames.map(frameName => ({ key: frameName })),
      frameRate: 2,
      repeat: -1
    });
    bandit.play(`bandit-${index + 1}-anim`);
  });
}

And this is how it looks:

This is so much simplier than before, as there are no physics involved - just managing timers, collecting keypresses and displaying animations.

West Bank Disassembly