如何检查鼠标是否在 p5js 中的数组中的对象上?

How to check if mouse is over an object in an array in p5js?

我有一组蚂蚁,我希望用户能够单击它们并查看单个蚂蚁的统计信息。我为一只蚂蚁制作了一个对象,并将其中几个蚂蚁对象放在屏幕上。当前,当我使用以下代码单击一只蚂蚁时:

function mouseClicked() {
  if(overAnt(ants[i].pos.x, ants[i].pos.y, ants[i].r)) {
    print('Health: ' + ant.health + '\nHunger: ' + ant.hunger + '\nThrist: ' + ant.thirst);
  }
}

它会给我一个错误,指出 'i' 未定义。我不太确定我做错了什么并且很困惑。这是项目其余部分的代码。

蚂蚁代码:

function Ant() {
  this.pos = createVector(random(50, 350), random(350, 50));
  this.vel = createVector();
  this.r = 20;
  
  let antNames = ['Gary', 'Lary', 'Jerry', 'Berry', 'Serry', 'Cari'];
  let word = random(antNames);
  
  this.name = word;
  
  this.health = 100;
  this.hunger = 0;
  this.thirst = 0;
  
  this.hDeplete = createVector(random(50, 1));
  
  this.show = function() {
    push();
    ellipseMode(CENTER);
    if(this.dead) {
      fill(255, 0, 0);
    } else if (!this.dead) {
      fill(0);
    }
    ellipse(this.pos.x, this.pos.y, this.r, this.r);
    pop();
  }
  
  this.update = function() {
    if(this.hunger < 100) {
      this.hunger += 1;
    } else if(this.hunger >= 85 && this.health != 0) {
      this.health -= 1;
      print('health going down ' + this.health);
      if(this.health == 0) {
        this.dead();
      }
    }
    
    
    
  } 

  this.dead = function() {
    if(this.health == 0) {
      fill(255, 0, 0);
      print(this.name + ' dead.');
      return true;
    } else {
      return false;
    }
  }
}

sketch.js代码:

let antNum = 10;

let i = 1;

function setup() {
  createCanvas(400, 400);
  
  ants = [];
  
  for(var i = 0; i < antNum; i++) {
    ants[i] = new Ant();
  }
  
  
}

function draw() {
  background(220);
  
  for(var i = 0; i < antNum; i++) {
    ants[i].show();
    ants[i].update();
  }
}

function overAnt(x, y, r) {
  if (dist(x, y, mouseX, mouseY) < r) {
    return true;
  } else {
    return false;
  }
}

function mouseClicked() {
  if(overAnt(ants[i].pos.x, ants[i].pos.y, ants[i].r)) {
    print('Health: ' + ant.health + '\nHunger: ' + ant.hunger + '\nThrist: ' + ant.thirst);
  }
}

(不要介意其他可怕且低效的代码哈哈)

如果值得一提的话,我已将 ant.js 文件添加到 index.html 文件中,因此除 mouseClicked 函数外,所有内容都被正确调用。 (另一个注意事项:mouseClicked 函数在它只是一个对象而不是它们的数组时工作得很好)

查看这段代码,它应该始终检查您是否单击了第二只蚂蚁,因为您已经在顶部定义了 i = 1。 所以我假设你是在收到你发布的错误后添加的。

你想要做的是在那个函数中定义i ,就像你在setupdraw中所做的那样,并且遍历所有蚂蚁,看看鼠标是否在其中任何一只蚂蚁之上:

function mouseClicked() {
  for(var i = 0; i < antNum; i++) {
    if(overAnt(ants[i].pos.x, ants[i].pos.y, ants[i].r)) {
      print('Health: ' + ant.health + '\nHunger: ' + ant.hunger + '\nThrist: ' + ant.thirst);
    }
  }
}

您还应该在代码的顶部定义 const ants = [],就像您对 antNum 所做的那样。