Home > Net >  Error in object generator via button in p5.js
Error in object generator via button in p5.js

Time:12-21

I am doing a logic gate simulator where I already have entities like switch, light and functions like wiring and more. But I wanted to create entities like switch and light via the button you click on and the object or entity will be created for you, but it doesn't work for me. Someone couldn't help me with that. Thanks in advance. The code I attach via the link will take you to the entire code and simulator in the online editor from p5.js.

Full Code: https://editor.p5js.org/jakubmitrega1/sketches/Mg1BGpimz

Relevant Code:

let entities = [];

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

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

CodePudding user response:

It is pretty obvious why this isn't working once you isolate the code in question:

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))
  }
}

Since you are passing the type of entity as an argument to the createEntity function, the logical thing to do would be to have it actually specify an argument and check that instead of 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 >
  <button onclick="createEntity('switch')">Switch</button>
  <button onclick="createEntity('light')">Light</button>
</div>

  • Related