You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Phaser游戏菜单按钮hover时setTint变为全黑问题求助

解决Phaser按钮悬停时setTint变黑的问题

你的问题出在两个核心点:回调函数的this指向错误,以及颜色值的传递方式存在兼容问题。

问题分析

  1. this指向偏差:普通function回调里的this并没有指向你的placeholder图片(不同Phaser版本可能指向场景或全局对象),导致setTint没有正确作用在目标元素上,触发了意外的全黑效果。
  2. 字符串颜色解析问题:Phaser对十六进制颜色字符串的解析在部分版本中存在兼容问题,改用数值形式的颜色值更可靠。

修复后的代码

class Scene2 extends Phaser.Scene{
    constructor(){
      super("playGame");
    }
  
    create() {
        this.cursors = this.input.keyboard.createCursorKeys()
        this.placeholder = this.add.image(250,200,"placeholder")
        this.placeholder.setOrigin(0,0)
        this.placeholder.setScale(2)
        this.placeholder.setInteractive()
        
        this.placeholder.on('pointerup', () => {
          console.log("YAY")
        })
        
        // 箭头函数确保上下文正确,直接操作placeholder
        this.placeholder.on('pointerover', () => {
          console.log('get off me bitchhh')
          this.placeholder.setTint(0x8D8E8F)
        })
        
        this.placeholder.on('pointerout', () => {
          console.log('thanks pookie')
          this.placeholder.setTint()
        })
        
        this.add.text(20, 20, "Playing game", {font: "25px Arial", fill: "yellow"});
    }
}

补充方案

如果偏好使用普通函数回调,可以手动指定回调的上下文:

this.placeholder.on('pointerover', function(){
  this.setTint(0x8D8E8F)
}, this.placeholder) // 第三个参数明确指定this指向placeholder

内容的提问来源于stack exchange,提问作者Owen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:45:56