Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
Getting last element on click every time in Javascript loop with Phaser JS

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

  • Here the docs to the forEach method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach, explains the index used
  • Here the docs to the Phaser on listener https://photonstorm.github.io/phaser3-docs/Phaser.GameObjects.Sprite.html#on__anchor, explains the passing of the context.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda