今天來講講滑鼠的監聽事件,在 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)
當知道滑鼠監聽,就可以去監聽各種事情的觸發,方便我們可以更多元化的操作遊戲
參考資料
這一篇除了講到滑鼠監聽以外,後面也有講到如何將寫好的東西封裝並重複使用,有興趣可以看看