sprite - Add sprite in function in Phaser 3
问题描述
I am adding a sprite to my game like this:
enemy = this.physics.add.sprite(280, 32, 'enemy');
Now I'd like to add it from inside a function like this:
spawn(this.enemy);
function spawn(enemy) {
enemy = this.physics.add.sprite(280, 32, 'enemy');
}
It doesn't work, I get the following error:
TypeError: this.physics is undefined
What do I have to write instead of this.physics
?
解决方案
You should, instead, use an arrow function like so:
First, within the function preload()
, add the sprite:
this.load.spritesheet('enemy', 'assets/enemy.png', { frameWidth: 32, frameHeight: 48 });
Second, within the function create()
, add the following code:
spawn = (enemyName) => {
enemyPlayer = this.physics.add.sprite(400, 450, enemyName);
}
spawn('enemy');
As you can see, we're passing the sprite's name as a function's parameter. You can, now, reuse this function to "spawn" other sprites. For example, spawn('stars')
.
推荐阅读
- jquery - Kibana 度量从最后一个日期值总结所有 num 值
- ruby-on-rails - NoMethodError:未定义的方法`url_prefix ='
- php - CakePHP 4.2 在 beforeSave 中获取登录用户
- python - for循环中没有图像显示
- python - Pandas:Python数据框为范围内的值绘制图表
- python - AttributeError:“DataFrame”对象没有属性“items”(pandas DataFrame 错误)
- scala - 移至 spark 3.0.1 后,“除外”功能无法按预期工作
- c++ - (C++) 如果用户已经在 main 中输入了值,如何将局部变量从 main 传递到另一个函数的主体?
- react-native - 如何使用 @react-navigation/native 删除 react native 中的上一页
- r - 当列不存在时运行代码(尽管最后有一个数字)?- 使困惑