通过 p5.js 中的按钮在对象生成器中出错

Error in object generator via button in p5.js

我正在做一个逻辑门模拟器,我已经有了开关、灯等实体和接线等功能。但是我想通过您单击的按钮创建开关和灯等实体,并且将为您创建对象或实体,但它对我不起作用。有人帮不了我。提前致谢。我通过 link 附加的代码将带您从 p5.js.

进入在线编辑器中的完整代码和模拟器

完整代码: https://editor.p5js.org/jakubmitrega1/sketches/Mg1BGpimz

相关代码:

let entities = [];

function createEntity() {
  if (mousePressed == "Light") {
    entities.push(new Switch(100, 100))
  }

  if (mousePressed == "Light") {
    entities.push(new Light(100, 200))
  }
}
<div class="menu">
  <button onclick="createEntity('switch')">Switch</button>
  <button onclick="createEntity('light')">Light</button>
</div>

很明显,一旦您隔离了有问题的代码,为什么这不起作用:

let entities = [];

function createEntity() {
  // Obvious typo here: "Light" instead of "Switch"
  // However, bigger issue, why would mousePressed be equal to any kind of
  // string at all? Much less one that will help you determine which button
  // was pressed.
  if (mousePressed == "Light") {
    entities.push(new Switch(100, 100))
  }

  if (mousePressed == "Light") {
    entities.push(new Light(100, 200))
  }
}

由于您将实体类型作为参数传递给 createEntity 函数,合乎逻辑的做法是让它实际指定一个参数并检查它而不是 mousePressed

let entities = [];

function createEntity(type) {
  // Note: string comparison is case sensitive.
  if (type === "switch") {
    alert("Create a Switch");
  } else if (type === "light") {
    alert("Create a Light");
  }
}
<div class="menu">
  <button onclick="createEntity('switch')">Switch</button>
  <button onclick="createEntity('light')">Light</button>
</div>