简体   繁体   中英

How can I add a for-loop in this scenario?

In my code, if I collide with bon1_mc , it adds points to my counter and plays a sound. Also if I collide 5 times with bon1_mc it stops the game and plays a soundtrack. How can I make it so it does the same thing with bon2_mc and bon3_mc (these are clips from my animate project)? I know I can use a for-loop, but I don't know how to incorporate it.

function fCollision(ennemi) {
  let collision = ndgmr.checkRectCollision(exportRoot.jeu_mc.moi_mc, ennemi);

  if (collision) {
    if (ennemi === exportRoot.jeu_mc.bon1_mc) { // Action si gagne
      points++;
      exportRoot.jeu_mc.points_txt.text = "Points : " + points;
      playSound("Bonc");

      if (points === 5) {
        playSound("Victoire");

        for (let x = 1; x <= 2; x++) {

          exportRoot.jeu_mc["mauvais" + x + "_mc"].removeEventListener("tick", fBougeEnnemis);
        }

        for (let x = 1; x <= 3; x++) {

          exportRoot.jeu_mc["bon" + x + "_mc"].removeEventListener("tick", fBougeBons);
        }

        document.removeEventListener("keydown", fQuelleTouche);
        document.removeEventListener("keyup", annuleTouche);
      }
    }
  }
}

Technically you don't have to do a loop, with your structure you can use an array of your objects then use array.indexOf to check against the array.

blocks is the array that I created from your objects, and I updated your if statement .

function fCollision(ennemi) {
       let blocks = [exportRoot.jeu_mc.bon1_mc,exportRoot.jeu_mc.bon2_mc,exportRoot.jeu_mc.bon3_mc];

        let collision = ndgmr.checkRectCollision(exportRoot.jeu_mc.moi_mc, ennemi);

        if (collision) {

            if (blocks.indexOf(ennemi) > -1) {       // Action si gagne
                points++;
                exportRoot.jeu_mc.points_txt.text = "Points : " + points;


                playSound("Bonc");

                if (points === 5) {
                    playSound("Victoire");


                    for (let x = 1; x <= 2; x++) {

                        exportRoot.jeu_mc["mauvais" + x + "_mc"].removeEventListener("tick", fBougeEnnemis);
                    }
                    for (let x = 1; x <= 3; x++) {

                        exportRoot.jeu_mc["bon" + x + "_mc"].removeEventListener("tick", fBougeBons);
                    }

                    document.removeEventListener("keydown", fQuelleTouche);
                    document.removeEventListener("keyup", annuleTouche);


                }

            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM