iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 7
0
Modern Web

關於你關於我關於phaser系列 第 7

Day7 phaser的滑鼠監聽

今天來講講滑鼠的監聽事件,在 phaser3 中,要讓目標物被監聽的話,要先 setInteractive,並用串聯的方式掛上監聽事件(有點類似用 js 掛監聽要先 addEventListener),而滑鼠有 4 種,pointerover (滑鼠進入) 、pointerout (滑鼠離開) 、pointerdown (滑鼠按下) 、pointerup (滑鼠放開) ,並且可以一個目標物被多個監聽,以下示範四種會觸發的狀況,並在 console 可以看到分別被觸發的時機

class playGame extends Phaser.Scene {
  create() {
    let clickCount = 0;
    this.clickCountText = this.add.text(100, 200, '');

    this.clickButton = new Phaser.GameObjects.Text(this, 100, 100, 'Click me!', {
      color: 'red'
    });
    this.add.existing(this.clickButton);
    this.clickButton
      .setInteractive({
        useHandCursor: true
      })
      .on('pointerover', () => this.enterButtonHoverState())
      .on('pointerout', () => this.enterButtonRestState())
      .on('pointerdown', () => this.enterButtonActiveState())
      .on('pointerup', () => {
        this.updateClickCountText(++clickCount);
      });

    this.updateClickCountText(clickCount);
  }

  updateClickCountText(clickCount) {
    console.log('>>>>>>>>>>>>>>button click')
    this.clickCountText.setText(`Button has been clicked ${clickCount} times.`);
  }

  enterButtonHoverState() {
    console.log('>button in')
  }

  enterButtonRestState() {
    console.log('>>>button out')
  }

  enterButtonActiveState() {
    console.log('>>>>>>button active')
  }
}

var config = {
  type: Phaser.AUTO,
  width: 480,
  height: 320,
  scene: [playGame]
}

var game = new Phaser.Game(config)

當知道滑鼠監聽,就可以去監聽各種事情的觸發,方便我們可以更多元化的操作遊戲

參考資料
這一篇除了講到滑鼠監聽以外,後面也有講到如何將寫好的東西封裝並重複使用,有興趣可以看看


上一篇
Day 6 第一個遊戲:完成遊戲啦
下一篇
Day 8 關於背景
系列文
關於你關於我關於phaser30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言