Having an issue passing sprite arguement to the .on

I’m struggling with callback functions within phaser. I know the arguements are always set to return pointer and position but why can’t I add the sprite from this function, to the next function… (even with apply)

Can anyone see a way around this? I need to access the sprite to see their abilities they have access to dependent on the model/class/level. Eveything else is set up find except this part which will be updating text dependant on model. Think final fantasy.

battleText(sprite, enemies) {

        sprite.menuText = [];

        sprite.menuText.push(this.add.text(this.gameWidth / 6, this.gameHeight / 6 * 4, 'Attack' )
            .setInteractive()
            .setPadding(10, 10, 10, 10)
            .setBackgroundColor('#FFFFFF')
            .setColor('#000000')
            .on('pointerdown', function() {

            }))

        sprite.menuText.push(this.add.text(this.gameWidth / 6, this.gameHeight / 6 * 5, 'Spells' )
            .setInteractive()
            .setPadding(10, 10, 10, 10)
            .setBackgroundColor('#FFFFFF')
            .setColor('#000000')
            .on('pointerdown', function(sprite) {
                console.log('hello')
            }, this))
        
        sprite.menuText.push(this.add.text(this.gameWidth - this.gameWidth / 3, this.gameHeight / 6 * 4, 'Items' )
            .setInteractive()
            .setPadding(10, 10, 10, 10)
            .setBackgroundColor('#FFFFFF')
            .setColor('#000000')
            .on('pointerdown', function(sprite) {
                console.log('hello')
            }, this))
        
        sprite.menuText.push(this.add.text(this.gameWidth - this.gameWidth / 3, this.gameHeight / 6 * 5, 'Escape' )
            .setInteractive()
            .setPadding(10, 10, 10, 10)
            .setBackgroundColor('#FFFFFF')
            .setColor('#000000')
            .on('pointerdown', function(sprite) {
                console.log('hello')
            }, this))

    }

:wave:

You can still access sprite in the callback function, as long as you don’t name a callback argument the same thing.

sprite.menuText = [];

sprite.menuText.push(
  this.add.text(this.gameWidth / 6, (this.gameHeight / 6) * 4, 'Attack')
    .setInteractive()
    .on('pointerdown', function () {
      console.log('The sprite is', sprite);
    })
);

Amazing thank you. Can I ask why this happens? Is it because its on an external function and being scoped it?

I ask because I know on some functions you need to add the arguments after the call back such as on overlaps and colliders

The inner function can still access the outer function’s variables.

With on() you can’t pass values to a callback. The event emitter always chooses which arguments the callback receives.

1 Like