如何仅从Js for循环中获得一个结果?

时间:2020-08-11 18:35:36

标签: javascript arrays for-loop

我正在用p5 lib编写一个小JS Zombie游戏。当您单击“僵尸”时,它应该计入点击;而当您错过一个时,它应该计入。但是,当阵列中有10个左右的僵尸时,每次点击给出10个结果。看起来很简单,但到目前为止我一直在解决这个问题。在用庞大的代码弄乱游戏之前,我需要一个适当的解决方案。 THX寻求帮助

git config core.ignoreCase               # check its value
git config --global core.ignoreCase true # set it globally
// object storing arrays

let zom = [];
let hb = 25;

// player info and ui
;
let hits = 0;
let missed = 0;


function setup() {
  let cnv = createCanvas(600, 300, P2D);



  let pos = createVector((width / 2), (height / 2));
  // zombie spawnpoints
  let zp0 = createVector(height / 4 + 35, height / 3);
  let zp1 = createVector(width - 35, height / 2);


  zom.push(new Zombie(zp0));
  zom.push(new Zombie(zp1));


}

function draw() {
  background(220);
  fill(0);
  text("hits: " + hits, 10, 10);
  text("missed: " + missed, 10, 20);
 

  for (let i = 0; i < zom.length; i++) {
    zom[i].move();
    zom[i].show();
  }

}

function Zombie(pos) {

  this.pos = pos;

  Zombie.prototype.move = function() {
    this.pos.x += 0.2;
    if (this.pos.x > width + hb) {
      this.pos.x = -hb

    }
  }
  Zombie.prototype.show = function() {

    circle(this.pos.x, this.pos.y, hb);

  }

}

function mouseClicked() {
  hitBox();
}

function hitBox() {
  let mx = mouseX;
  let my = mouseY;
  for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
      mx < zom[i].pos.x + hb &&
      my > zom[i].pos.y - hb &&
      my < zom[i].pos.y + hb) {


      hits += 1;

    } else {

      missed += 1;
    }
  }
}
 

2 个答案:

答案 0 :(得分:0)

我认为您的问题是,您只需单击一下即可遍历所有僵尸,并将其设置为每+1个未命中或+1个命中。

您应该有一种方法可以返回命中率或未命中率,并且可以计算+1未命中或+1命中率。

这是一个伪示例:

mouseclick...{
if(isHit()){
 hits+= 1
 }else{
 missed+=1
}

}

function isHit(){
 let mx = mouseX;
 let my = mouseY;
 for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
      mx < zom[i].pos.x + hb &&
      my > zom[i].pos.y - hb &&
      my < zom[i].pos.y + hb) {
  return true
} 
}
return false
}

答案 1 :(得分:0)

您要做的是,如果任何僵尸被击中,则增加hits;如果 all 未击中,则增加missed >僵尸。为此,您可以循环遍历所有僵尸,并在遇到任何僵尸后立即计数一次命中;如果您完成了整个循环并且没有命中,则计算未命中次数

function hitBox() {
  const mx = mouseX;
  const my = mouseY;
  for (let i = 0; i < zom.length; i++) {

    if (mx > zom[i].pos.x - hb &&
        mx < zom[i].pos.x + hb &&
        my > zom[i].pos.y - hb &&
        my < zom[i].pos.y + hb)
    {
      // Count the hit and return from the function if this zombie was hit
      hits += 1;
      return;
    }

    // We'll only reach this line if the loop completed
    // without counting a hit and returning.
    // In that case, this was a miss.
    missed += 1;
  }
}

确实假定一次只能击中一个僵尸(两个僵尸不能占据相同的空间)