首页 > 解决方案 > 当我使用 game.load 时,为什么我得到“未定义”的“加载”?(Vue + 移相器)

问题描述

我使用 Vue + Phaser 开始了新项目,但是当我尝试加载资产时,this.game.load.image 中的“加载”和“添加”返回“未定义”。我尝试从 JS 文件中导入预加载函数,但我得到了同样的错误。如果我在没有 Vue 的情况下对其进行测试,我的 Phaser 代码不会返回错误,它是正常的。

游戏.vue:

import Phaser from 'phaser'
export default {
name: 'Game',
data: () => ({
    game: null,
    sprites: {}
}),
mounted () {
    const self = this
    if (this.game == null) {
        this.game = new Phaser.Game({
            type: Phaser.AUTO,
            width: window.innerWidth,
            height: window.innerHeight,
            antialias: true,
            parent: this.$el,
            physics: {
                default: 'arcade',
                arcade: {
                    gravity: { 
                        y: 300 
                    },
                    debug: false
                }
            },
            scene: {
                preload: function preload() {
                    self.preload(this)
                },
                create: function create() {
                    self.create(this)
                },
                update: function update() {
                    self.update(this)
                },
                render: function render() {
                    self.render(this)
                }
            }
        })
    }
},
methods: {
    preload () {
        this.game.load.setBaseURL('http://labs.phaser.io')

        this.game.load.image('sky', 'src/games/firstgame/assets/sky.png')
        this.game.load.image('ground', 'src/games/firstgame/assets/platform.png')
        this.game.load.spritesheet('dude', 'src/games/firstgame/assets/dude.png', { frameWidth: 32, frameHeight: 48 })
        this.game.load.spritesheet('monster', 'src/games/firstgame/assets/dude.png', { frameWidth: 32, frameHeight: 48 })
    },
    create (phaser) {
        let self = this
        console.log(self, phaser, this.game)
        this.game.add.image(0, 0, 'sky').setOrigin(0,0).setScale(4);
    },
    listener (e) {
        console.log('listener', e)
    },
    update () {

    },
}
}

对不起我的英语错误

标签: javascriptvue.jsphaser-framework

解决方案


我猜你正在使用 Webpack/Vue-CLI?

如果是这种情况,请将这些资产作为模块导入并在加载程序调用中引用导入。

import sky from 'src/games/firstgame/assets/sky.png'

// in your preload method:
this.game.load.image('sky', sky)

这是必要的,因为 Webpack 需要将源文件夹中的图像路径替换为构建的输出目录中的图像路径。

https://webpack.js.org/guides/asset-management#loading-images

另外,请查看我的 Vue/Phaser Webpack 模板,该模板已为您准备好一切以开始使用。

https://github.com/Sun0fABeach/vue-phaser3


推荐阅读