"Cannot read property 'sprite' of undefined"?

I got this error, how can I fix it?
I’m trying to spawn sprites.

function citizen(x,y) {
	guy = this.add.sprite(x, y,'guy');
	this.anims.create({
		key: 'walk',
		frames: this.anims.generateFrameNumbers('guy', {start: 0, end: 7}),
		frameRate: 7,
		repeat: -1
	});
	guy.anims.play('walk',true);
}

mainscene.create = function() {
	citizens = this.add.group();
	ct = this.time.addEvent({
	  delay: 4000,
	  callback: function() {let citiz = new citizen(100,397);this.citizens.add(citiz);},
	  callbackScope: this,
	  loop: true
	});

PS I tried spawning directly inside the timer but I find this way works for me better

THANKS

Hmmm… the scope of ‘this’ is not passed to citizen() function. You will need to pass ‘this’ to the citizenship function or bind it.

1 Like

I’m sorry but I really don’t know how to do that. can you tell me how ? if it’s like this function citizen(this,x,y) it didn’t work

you could try something like this

function citizen(scene, x,y) {
guy = scene.add.sprite(x, y,'guy');
scene.anims.create({
	key: 'walk',
	frames: scene.anims.generateFrameNumbers('guy', {start: 0, end: 7}),
	frameRate: 7,
	repeat: -1
});
guy.anims.play('walk',true);
}

mainscene.create = function() {
	citizens = this.add.group();
	ct = this.time.addEvent({
	  delay: 4000,
	  callback: function() {let citiz = new citizen(this, 100,397);this.citizens.add(citiz);},
	  callbackScope: this,
	  loop: true
	});
1 Like
  • You need to create an animation only once, not once for each sprite.
  • Don’t use new with citizen(). Instead citizen() should create and return a new sprite (I think).
var citizens;
var ct;
var mainscene;

function newCitizen(scene, x, y) {
  var guy = scene.add.sprite(x, y, 'guy');

  guy.anims.play('walk', true);

  return guy;
}

mainscene.create = function() {
  this.anims.create({
    key: 'walk',
    frames: this.anims.generateFrameNumbers('guy', { start: 0, end: 7 }),
    frameRate: 7,
    repeat: -1
  });

  citizens = this.add.group();

  ct = this.time.addEvent({
    callback: function() {
      citizens.add(newCitizen(this, 100, 397));
    },
    delay: 4000,
    loop: true,
    callbackScope: this
  });
};
1 Like

thanks a lot guys