如何使if语句只为真一次? [英] How to make if statement true only once?

查看:291
本文介绍了如何使if语句只为真一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使if语句只运行一次。我正在用javascript制作一个游戏,一旦用户得分为5,我想在阵列中添加一个新的敌人。我遇到的问题是,如果if语句为真,它会不断添加新的敌人,直到整个屏幕被敌人覆盖。我希望它在得分为5时只添加1个新敌人,然后在得分为10时添加另一个敌人等等。我无法想到实现这一目标的方法。谢谢。

How do I make an if statement run only once. I am making a game in javascript and once the users score is 5 I want to add a new enemy into the array. The problem I am having is once the if statement is true it keeps adding new enemies over and over until the whole screen is covered with enemies. I want it to add only 1 new enemy when score is 5 then another when score is 10 and so on. I cannot think of a way to accomplish this. Thank You.

Sketch.js

Sketch.js

   var score = 0;

   //3 three enemies once game starts
   function StartingEnemies() { 
      for (var i = 0; i < 2; i++) {
        enemies[i] = new BasicEnemy();
      }
   }


   //add new enemies into the array
   function spawnNewEnemies() {
     enemies.push(new BasicEnemy());
   }


   if (score == 5) {
     spawnNewEnemies();
   }


推荐答案

var addNew=true;
if (score == 5 && addNew) {
  spawnNewEnemies();
  addNew=false;
}

如果您正在运行函数内部的代码,请确保addNew是在某个地方声明它会在通话之间保持不变。

If you are running the code inside of a function, make sure that addNew is declared somewhere that it will persist between calls.

这篇关于如何使if语句只为真一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆