javascript - 在这种情况下如何添加 for 循环?
问题描述
在我的代码中,如果我与 碰撞bon1_mc
,它会向我的计数器添加点并播放声音。此外,如果我与它碰撞 5 次,bon1_mc
它会停止游戏并播放配乐。我怎样才能使它与bon2_mc
和bon3_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);
}
}
}
}
解决方案
从技术上讲,您不必执行循环,您可以使用您的结构使用对象数组,然后使用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);
}
}
}
}
推荐阅读
- mysql - 如何从mysql中的group by和groupconcat其他字段中获取最大值?
- python - 数据集中的新列基于项目的最后一个值
- video-streaming - 从一个接口到另一个接口的多播路由
- gradle - 我可以获得有关 Gradle 7.0 中“隐式依赖项”的更多信息吗?
- windows-installer - 静默安装 Visual Studio 2019 构建工具的问题
- sql - 返回类型的函数多次运行
- continuous-integration - 快速通道的 Gitlab Runner 问题
- java - 如何创建 SonarQube 插件以添加自定义 XML 规则?
- react-native - 如何在 React Native MapView 中选择默认的谷歌地图标记?或者,您如何不显示默认的 Google 地图标记?
- python - 如何从python列表中的点列表中获取方程?