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

Phaser框架中更新圆形图片尺寸时旧版本残留问题求助

解决Phaser中圆形残留的同心环问题

核心问题是你在update()函数里重复创建图形元素——update()每帧都会执行,每次调用this.add.image()都会生成新的红色圆形和home图像,旧元素没有被销毁,自然叠加出同心环效果。

修复步骤:

  • 将静态元素的创建逻辑移到create()方法中(这个方法只在场景初始化时执行一次)
  • 在update()里仅做状态判断和元素属性更新(比如缩放、可见性)

修改后的代码示例:

// 场景初始化时执行一次
create() {
    let config = this.game.config
    let canvas_height = config.height
    let canvas_width = config.width
    this.cameras.main.setBounds(
        -canvas_width/ 2,
        -canvas_height/ 2,
        canvas_width,
        canvas_height);

    // 只创建一次红色圆形,初始隐藏
    this.return_circle = this.add.image(0, 0, 'red').setInteractive()
    this.return_circle.setVisible(false)

    // 只创建一次home图像,不需要每帧都新建
    this.invisible_home = this.add.image(0, tablet_floor, 'home').setInteractive()
}

// 每帧更新时执行
update() {
    let config = this.game.config
    let pointerpoint

    if (state == 'stop') {
        const endPoint = {x:end_pos_x, y:end_pos_y}
        const pointer = this.input.activePointer

        let px = pointer.x - (config.width/2)
        let py = pointer.y - (config.height/2)
        pointerpoint = {x: px, y: py}

        // 计算缩放比例
        let size = Phaser.Math.Distance.BetweenPoints(pointerpoint, this.invisible_home) 
                  / Phaser.Math.Distance.BetweenPoints(endPoint, this.invisible_home)

        // 更新圆形的缩放和可见性
        this.return_circle.setScale(size).setVisible(true)
    } else {
        // 非stop状态时隐藏圆形
        this.return_circle.setVisible(false)
    }
}

关键说明:

  • 用this.return_circle和this.invisible_home把元素挂载到场景实例上,这样update里能直接访问
  • 避免在update里调用add.image(),防止重复创建元素
  • 统一在update的else分支处理圆形隐藏逻辑,确保状态切换时旧元素会被隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:03:27