2

I am making a game in Phaser although I believe the core of this issue is a lack of my JS understanding.

I am looping through a Phaser container and wish to apply a click handler on each child sprite, but when I execute the click on any of the sprites, it always returns the last child.

I have tried various suggestions on Stack Overflow eg here: JavaScript closure inside loops – simple practical example

but can never get the click to return anything other than the last item.

An Example:

let items = //my container with 4 child sprites to click on
let i = 0;
item.list.forEach(function(obj) {
    obj.setInteractive();
    (function(i) {
        obj.on('pointerdown', function(i){
            console.log(i);
        }.bind(this, i));
    })(i);
    i++;
});

In this example, every sprite I click on outputs '3' tot he console, when it should output 0,1,2 or 3 depending on which was clicked.

karatecode
  • 574
  • 6
  • 21

1 Answers1

1

Your code is abit complicated. If you just want to add a EventHandler just, you don't need an extra closure. Just check the code below, for a leaner approach

Working example:

// Minor formating for stackoverflow
    document.body.style = "display: flex;flex-direction: column;";    

    var config = {
        type: Phaser.AUTO,
        width: 536,
        height: 183,
        scene: {
            create
        },
        banner: false
    }; 

    function create () {
        let items = this.add.container(10, 10);
        items.add(this.add.sprite(20, 20, 'sprite'));
        items.add(this.add.sprite(20, 60, 'sprite'));
        items.add(this.add.sprite(20, 100, 'sprite'));
        items.list.forEach(function(obj, index) {
            obj.setInteractive();
            obj.on('pointerdown', function(){
                console.log(`You clicked: sprite with index ${index}`);
            }, this); // although I don't know why you would want do bind this "this"
       });
    }

    var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js">
</script>
winner_joiner
  • 12,173
  • 4
  • 36
  • 61
  • Thanks, the complexity is the result of suggestions in the thread I linked to. I had started with your example and it always returns '3' for the index. I'm guessing it must be something deeper in the application causing it than this snippet. – karatecode Mar 26 '22 at 13:01
  • @web_la my example doesn't always returns '3'. here is a full working example. – winner_joiner Mar 26 '22 at 15:37
  • I update the answer – winner_joiner Mar 26 '22 at 15:51
  • Turns out my specific problem was I had part of an invisible png overlaying everything with the index of three which was always getting clicked. Answer is technically correct of course – karatecode Mar 26 '22 at 21:05