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

Phaser 3升级卡片类导入后无显示且无报错问题求助

问题解决:Phaser 3升级卡片类无法显示的问题

你核心的错误是把升级卡片定义成了Scene类——Scene是Phaser中独立的场景单元(比如主菜单、游戏场景),不能直接作为游戏对象添加到另一个Scene里。你实例化了Scene但没有启动它,而且add.existing不支持添加Scene,所以既不显示也不报错。

正确的做法是让升级卡片继承Phaser.GameObjects.Container,因为Container可以将图片、文本等多个元素打包成一个可管理的整体,完美适配升级卡片这种UI组件的需求。

修改后的代码实现

1. 升级卡片类(increase_speed.js)

export default class IncreaseSpeed extends Phaser.GameObjects.Container {
    constructor(scene, x, y) {
        // 调用Container构造函数,传入父场景、卡片的x/y坐标
        super(scene, x, y);
        
        // 创建卡片背景(坐标相对于容器中心)
        this.bg = scene.add.image(0, 0, 'cardbg');
        // 创建标题文本
        this.title = scene.add.text(-65, -100, '提升\n速度', {
            fontFamily: 'dogicaPixel',
            fontSize: '20px',
            align: 'center'
        });
        // 创建描述文本
        this.description = scene.add.text(-80, 0, '提升角色移动速度\n持续整场游戏', {
            fontFamily: 'dogicaPixel',
            fontSize: '15px',
            align: 'center'
        });
        // 创建升级按钮
        this.upgradeBtn = scene.add.text(-65, 120, '升级', {
            fontFamily: 'dogicaPixel',
            fontSize: '20px',
            align: 'center'
        });
        
        // 将所有元素添加到容器中
        this.add([this.bg, this.title, this.description, this.upgradeBtn]);
        
        // 给按钮添加交互(可选,处理升级逻辑)
        this.upgradeBtn.setInteractive({ useHandCursor: true });
        this.upgradeBtn.on('pointerdown', () => {
            // 这里写入你的升级逻辑,比如修改角色速度
            scene.player.speed += 50;
            console.log('速度已提升!当前速度:', scene.player.speed);
            // 可以添加卡片消失动画或其他反馈
            this.destroy();
        });
        
        // 将容器注册到父场景
        scene.add.existing(this);
    }
}

2. 升级场景调用(upgradeScene.js)

import IncreaseSpeed from './increase_speed.js';
// 导入另外两个升级类,比如IncreaseDamage、IncreaseHealth

export default class UpgradeScene extends Phaser.Scene {
    constructor() {
        super('upgradeScene');
    }
    
    preload() {
        // 统一加载卡片背景资源(不要在每个卡片类里重复加载)
        this.load.image('cardbg', './Assets/UI/cardbg.png');
    }
    
    create() {
        // 创建三个升级卡片,分别放在屏幕不同位置
        new IncreaseSpeed(this, 250, 400);
        // new IncreaseDamage(this, 500, 400);
        // new IncreaseHealth(this, 750, 400);
    }
}

关键注意事项

  • 资源加载:所有共享资源(比如卡片背景)要在父场景或全局预加载场景中加载,避免重复加载浪费资源
  • 实例独立性:用this.xxx替代全局变量,确保每个升级卡片实例都是独立的,不会互相干扰
  • 交互逻辑:通过setInteractive()给按钮添加点击事件,在回调中处理具体的升级逻辑
  • 布局调整:文本的坐标是相对于容器中心的,可以根据卡片背景的尺寸调整文本位置,确保显示居中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:05:29