【问题标题】:Self-hosted phaser 3 library: this is undefined?自托管 Phaser 3 库:这是未定义的吗?
【发布时间】:2022-01-30 18:13:17
【问题描述】:

对 Phaser 3 完全陌生

我已经用 npm 安装了这个库。然后我天真地从 node_modules 中获取捆绑的文件。

<body>
    <script src="./node_modules/phaser/dist/phaser-arcade-physics.js"></script>
    <script src="./js/start.js"></script>
</body>

当我在浏览器中加载 index.html 作为文件时,它工作正常。但现在我在我的 Apache 中创建了一个小 v-host 并让它为文件提供服务。这也有效,但移相器对我大喊:

Uncaught TypeError: this.texture is undefined
    setFrame http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:138726
    setTexture http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:138699
    Image http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:29328
    <anonymous> http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:168386
    create http://game.localhost/personwar/js/start.js:34
    [...]
    DOMContentLoaded http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:86811
    Game http://game.localhost/personwar/node_modules/phaser/dist/phaser-arcade-physics.js:154945
    <anonymous> http://game.localhost/personwar/js/start.js:17

我从beginner tutorial 窃取了 start.js,一切从这里开始:

function create () {
    console.log('this', this);
    this.add.image(0, 0, 'bg').setOrigin(0, 0);
    ...
}

我不明白,为什么 this.texture 在库是自托管时会发生变化,而不是由 file:// 提供。我需要在这里更改什么?

这可能是时间问题,也许我需要在 create 回调中调用 this.add.image 之前进行设置。

我会继续调查,纹理到底是什么。

问题是 Header,由服务器设置:Content-Security-Policy

​​>

规则"default-src 'self'; style-src 'self' 'unsafe-inline'; object-src 'none'"

屏蔽了这个电话

blob:http://game.localhost/b6ac3ad7-e25b-4b82-8d07-8f4ce6c331c3

这是对我们其中一张图片的调用。这很奇怪,我不明白。但重点是:没有加载图像 -> 没有纹理

【问题讨论】:

    标签: javascript phaser-framework self-hosting


    【解决方案1】:

    好吧,我不知道您链接的是哪个文件。主移相器文件称为 phaser.jsphaser.min.js。我认为这是您问题的根源。

    简单的解决方案是将移相器 javascript 文件下载到您的 web 文件夹中,或从 cdn 链接它。 (https://phaser.io/download/stable)

    如果你(想)使用 npm,你将需要一个像 webpack、parcel 之类的打包工具,...那里。 (比如这个https://github.com/photonstorm/phaser3-project-template)。

    顺便说一句: 我不是专家,但我通常不会在网络服务器可访问文件夹中拥有 node_modules 目录(如果不是真的需要,并且如果您正在运行apache,可能不需要),因为这可能会带来潜在的安全风险。

    【讨论】:

    • 文件已正确传递:github.com/photonstorm/phaser/blob/master/dist/phaser.js setFrame (ll. 146449ff) 中出现问题:this.texture 未定义。所以我的问题是错误的,我会解决它。这可能是时间问题? setFrame 在我的create 回调中被调用,通过this.add.image
    • 呃,我找到了问题和解决方法,请参阅编辑!
    • 没有看到整个代码很难找到错误。如果原始示例代码不能自托管运行,则说明您的设置代码不正确,如果可以正常运行,则说明移相器代码有问题。
    • @BairDev 很高兴阅读它的工作原理。谢谢分享。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2020-07-27
    • 2021-11-04
    • 2019-01-08
    • 2020-06-15
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多