Pobtastic / Phaser Guide / Controls

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

Introduction

Keeping it very simple for now, it’s just:

  • Set the bandit sprites as being “interactive” which tracks them being clicked
  • Set a handler for keypresses

Either of these will auto-start the “being shot” animations:

create() {
  // 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`
    );
    // Handle mouse/ trackpad click inputs.
    bandit.setInteractive();
    bandit.on('pointerdown', () => this.triggerBandit(i - 1));
    // The animation is actually only the final part of the bandit being shot.
    // We can handle "drawing" slightly differently (later).
    bandit.frameNames = Array.from({length: 2}, (_, f) => `bandit-${i}-${f+3}`);
    this.bandits.push(bandit);
  }
  // Handle keyboard inputs.
  this.input.keyboard.on('keydown', (event) => {
    if (event.key === '1' || event.key === 'Numpad1') this.triggerBandit(0);
    if (event.key === '2' || event.key === 'Numpad2') this.triggerBandit(1);
    if (event.key === '3' || event.key === 'Numpad3') this.triggerBandit(2);
  });
}
triggerBandit(index) {
  // Very basic for this demo.
  const bandit = this.bandits[index];
  // Play the animation (only if it isn't already playing).
  if (!bandit.anims.isPlaying) {
    bandit.play(`bandit-${index + 1}-anim`);
  }
}

As before though, and for demo purposes only, I’m going to reset the initial sprite - so this demo can play over-and-over:

triggerBandit(index) {
  // Very basic for this demo.
  const bandit = this.bandits[index];
  // For this demo only; reset back to the first sprite if the animation has finished.
  bandit.on('animationcomplete', () => {
    bandit.setTexture(`bandit-${index + 1}-1`);
  });
  // Play the animation (only if it isn't already playing).
  if (!bandit.anims.isPlaying) {
    bandit.play(`bandit-${index + 1}-anim`);
  }
}

West Bank Disassembly