这是我的代码:
Create (){
spawn();
}
function spawn(){
var sprite = this.physics.add.sprite(50,50,'spritesheet','red.png');
}
现在运行此代码时,我会收到一个错误:
uck offult typeError:无法读取未定义的
的属性'添加'问题在于该函数的精灵部分,但是当我直接在创建函数中使用相同的代码时,它会起作用。因此,我该如何使其在外部功能中起作用。
如注释:
在Create()
中,this
与spawn()
中的this
不同。
因此,它需要在这些功能之间正确绑定。做到这一点的一种方法:
Create() {
spawn.bind(this)
spawn();
}
class myScene extends Phaser.Scene {
constructor (config)
{
super(config);
}
preload ()
{
this.load.image('dude', 'sprites/phaser-dude.png')
}
create ()
{
this.spawn()
}
spawn()
{
var sprite = this.physics.add.sprite(50, 50, 'dude')
}
}
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
loader: {
baseURL: 'https://cdn.jsdelivr.net/gh/samme/phaser-examples-assets@v2.0.0/assets/',
crossOrigin: 'anonymous'
},
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 1 }
}
},
};
var game = new Phaser.Game(config);
game.scene.add('myScene', myScene, true);
<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>