首页 > 解决方案 > 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?

标签: spritephaser-framework2d-games

解决方案


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').


推荐阅读