Estoy haciendo un simulador de puerta lógica donde ya tengo entidades como interruptor, luz y funciones como cableado y más. Pero quería crear entidades como el interruptor y la luz a través del botón en el que hace clic y el objeto o la entidad se crearán para usted, pero no funciona para mí. Alguien no pudo ayudarme con eso. Gracias por adelantado. El código que adjunto a través del enlace lo llevará al código completo y al simulador en el editor en línea de p5.js.
Código completo: https://editor.p5js.org/jakubmitrega1/sketches/Mg1BGpimz
Código relevante:
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>Es bastante obvio por qué esto no funciona una vez que aíslas el código en cuestión:
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)) } } Dado que está pasando el tipo de entidad como argumento a la función createEntity , lo lógico sería hacer que realmente especifique un argumento y verifique que en lugar de 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>