当这是一个不同的范围时,如何从碰撞器方法调用 class 中的函数?
How can I call a function in a class from a collider method when this is a different scope?
我正在使用 WebPack 构建我的游戏,但我 运行 遇到了范围界定问题。我会试着解释一下。
我的 TestScene class 文件:
import 'phaser';
import Npcs from 'modules/Npcs.js';
const npcs = new Npcs()
export class TestScene extends Phaser.Scene {
constructor () {
super('TestScene')
}
preload(){...}
create(){
this.physics.add.collider(
this.player,
this.bombs,
npcs.hitBomb,
null,
this
)
}
}
我的 Npcs class 文件:
import 'phaser';
const gameplayStates = new GameplayStates()
export default class Npcs {
hitBomb (player, bomb) {
this.physics.pause();
player.setTint(0xff0000);
this.entityDestroy()
}
entityDestroy () {
console.log('destroyed')
}
}
this.player
和 this.bombs
已就位,并按我预期的方式工作。
collider 方法中的回调将 this
(testScene) 作为上下文,因此 this.entityDestroy()
似乎不再起作用并引发错误:
app.bundle.js:116068 Uncaught TypeError: this.entityDestroy is not a function
。
我怀疑这是因为从碰撞器调用该方法时,npcs
class 不在 this
的范围内。
使用对撞机方法解决这个问题的正确方法是什么?
谢谢大家,
非常感谢您的帮助。
MHC
我在 www 上询问过,得到了一个令人满意的解决方案。
我得到最多的主要解决方案是更改碰撞器方法中的上下文。像这样:
this.physics.add.collider(
this.player,
this.bombs,
npcs.hitBomb,
null,
npcs
)
npc class 成为 hitBomb 函数的上下文。该解决方案的问题是我无法再在 npcs 函数中引用 this
(场景引用)。
我发现的最好的解决方法是:
this.physics.add.collider(
this.player,
this.bombs,
function (player, bomb) {
this.physics.pause();
npcs.hitBomb(player, bomb);
},
null,
this
)
这有更多行代码,但它允许我保留我从中调用碰撞器函数的场景范围并建立 npc 的范围 class。
感谢所有花时间与我聊天并帮助我找到解决方案的人。
我正在使用 WebPack 构建我的游戏,但我 运行 遇到了范围界定问题。我会试着解释一下。
我的 TestScene class 文件:
import 'phaser';
import Npcs from 'modules/Npcs.js';
const npcs = new Npcs()
export class TestScene extends Phaser.Scene {
constructor () {
super('TestScene')
}
preload(){...}
create(){
this.physics.add.collider(
this.player,
this.bombs,
npcs.hitBomb,
null,
this
)
}
}
我的 Npcs class 文件:
import 'phaser';
const gameplayStates = new GameplayStates()
export default class Npcs {
hitBomb (player, bomb) {
this.physics.pause();
player.setTint(0xff0000);
this.entityDestroy()
}
entityDestroy () {
console.log('destroyed')
}
}
this.player
和 this.bombs
已就位,并按我预期的方式工作。
collider 方法中的回调将 this
(testScene) 作为上下文,因此 this.entityDestroy()
似乎不再起作用并引发错误:
app.bundle.js:116068 Uncaught TypeError: this.entityDestroy is not a function
。
我怀疑这是因为从碰撞器调用该方法时,npcs
class 不在 this
的范围内。
使用对撞机方法解决这个问题的正确方法是什么?
谢谢大家,
非常感谢您的帮助。 MHC
我在 www 上询问过,得到了一个令人满意的解决方案。
我得到最多的主要解决方案是更改碰撞器方法中的上下文。像这样:
this.physics.add.collider(
this.player,
this.bombs,
npcs.hitBomb,
null,
npcs
)
npc class 成为 hitBomb 函数的上下文。该解决方案的问题是我无法再在 npcs 函数中引用 this
(场景引用)。
我发现的最好的解决方法是:
this.physics.add.collider(
this.player,
this.bombs,
function (player, bomb) {
this.physics.pause();
npcs.hitBomb(player, bomb);
},
null,
this
)
这有更多行代码,但它允许我保留我从中调用碰撞器函数的场景范围并建立 npc 的范围 class。
感谢所有花时间与我聊天并帮助我找到解决方案的人。