Phaser 3中如何提取image对象texture键名实现按钮匹配校验

初始示例代码:
const CButton = this.add.image(0, 0, 'C').setInteractive() const OButton = this.add.image(0, 0, 'O').setInteractive()

问题说明
需要在Phaser 3中提取image游戏对象绑定的texture键名,以此判断用户点击的按钮是否和前端展示的随机字符串匹配。
附完整原有代码:
create 函数原有代码
startTime = new Date(); var characters = 'CO'; var position = [57, 63]; var result = "" var chaactersLength = characters.length; for (var i = 0; i < 1; i++) { result += characters.charAt(Math.floor(Math.random() * chaactersLength)); }; const CButton = this.add.image(0, 0, 'C').setInteractive({ cursor: 'url(cursor/hand.cur), pointer' }); const OButton = this.add.image(0, 0, 'O').setInteractive({ cursor: 'url(cursor/hand.cur), pointer' }); this.aGrid = new AlignGrid({ scene: this, rows: 11, cols: 11 }); this.text = this.add.text(0, 0, "Test Count: " + loop, { font: "20px Arial", fill: 'black' }); this.aGrid.placeAtIndex(0, this.text); this.text = this.add.text(0, 0, result, style); this.aGrid.placeAtIndex(position[Math.floor(Math.random() * position.length)], this.text); this.aGrid.placeAtIndex(102, CButton); this.aGrid.placeAtIndex(106, OButton); this.time.addEvent({ callback: () => { loop++; CButton.on('pointerdown',() => this.scene.start("scene1") + end(), CButton) OButton.on('pointerdown',() => this.scene.start("scene1") + end(), OButton) } })
end() 函数原有代码
endTime = new Date(); var timeDiff = endTime - startTime; //单位为毫秒 // 转换为秒级单位 timeDiff /= 1000; // 取整得到秒数 var seconds = Math.round(timeDiff); console.log(seconds + " seconds");
项目逻辑:随机字符串由result变量生成,随机输出C或O的纹理键,需要检测用户点击的按钮纹理键是否和随机值匹配,以此实现对应判断逻辑。
解答
Phaser 3中完全可以直接提取Image对象绑定的纹理键名,直接访问实例的texture.key属性即可拿到创建时传入的纹理键字符串。
针对现有代码,有两处需要修正:
- 不需要把按钮的
pointerdown事件绑定套在time.addEvent回调里,会导致事件重复绑定,直接在create阶段绑定一次即可。 - 原有事件回调里
this.scene.start("scene1") + end()的写法错误,加号无法实现两个逻辑顺序执行,需要写在代码块里按顺序调用。
修改后的事件绑定代码如下:
// 移除原有的time.addEvent包裹,直接在create阶段绑定事件 const checkMatch = (btnKey) => { if (btnKey === result) { // 此处写匹配成功的业务逻辑,比如计分、正确提示 console.log('选项匹配正确') } else { // 此处写匹配失败的业务逻辑,比如错误提示、扣分 console.log('选项匹配错误') } end() this.scene.start("scene1") } CButton.on('pointerdown', () => checkMatch(CButton.texture.key)) OButton.on('pointerdown', () => checkMatch(OButton.texture.key))
如果要精简代码,也可以把两个按钮存入数组遍历绑定,减少重复代码:
const buttonList = [CButton, OButton] buttonList.forEach(btn => { btn.on('pointerdown', () => { if (btn.texture.key === result) { // 匹配成功逻辑 } else { // 匹配失败逻辑 } end() this.scene.start("scene1") }) })
内容的提问来源于stack exchange,提问作者Ng Jia Yong
相关产品推荐
相关产品推荐

