首页 > 解决方案 > 在这种情况下如何添加 for 循环?

问题描述

在我的代码中,如果我与 碰撞bon1_mc,它会向我的计数器添加点并播放声音。此外,如果我与它碰撞 5 次,bon1_mc它会停止游戏并播放配乐。我怎样才能使它与bon2_mcbon3_mc(这些是我的动画项目中的剪辑)做同样的事情?我知道我可以使用 for 循环,但我不知道如何合并它。

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);
      }
    }
  }
}

标签: javascriptfor-loop

解决方案


从技术上讲,您不必执行循环,您可以使用您的结构使用对象数组,然后使用array.indexOf该数组检查该数组。

blocks是我从您的对象创建的数组,我更新了您的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);


                }

            }
        }
    }

推荐阅读