1

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?

James Skemp
  • 8,018
  • 9
  • 64
  • 107
Hade0011
  • 81
  • 3
  • 10

1 Answers1

3

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68