Estoy tratando de resolver una tarea escolar en p5 JavaScript. Quiero que algo se mueva sobre el lienzo después de un clic del mouse. Pero solo se mueve un poco y tengo que hacer clic varias veces para que llegue al final. ¿Qué he hecho mal? ¿No debería el lazo hacer que se mueva completamente? Puede publicar el código completo si es necesario.
function CanvasPressed() { if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < 100 ) { Bird.stop(); Bird.play(); for ( let b = 640; b > 0; b--) { x = x - 0.05; } }Muy bien, entonces tienes un par de cosas mal entendidas, aquí:
// purely aesthetic but in javascript functions are usually written as (i think) camelCase // so: canvasPressed() rather than CanvasPressed(), Class-es start with upper case function CanvasPressed() { // you can check for width & height if you want if ( mouseX > 0 && mouseX < width) if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < height ) { for ( let b = 640; b > 0; b--) // this, in this case, does the same as for(let i = 0; i < width; i ++) { x += 0.05 // 0.05 is very little, only a very small part of a pixel } // here it moves 0.05 * 640 (0.05 + 0.05 + 0.05 ... ) } }convenciones de nomenclatura javascript cosita si quieres
y así es como lo haría moverse a través del lienzo:
let mouseWasPressed = false; let x = 20 function draw() { background(20); ellipse(x, height / 2, 40) if(mouseWasPressed) // don't need {} for 1 line after the if() x ++; // x = x + 1 shortening in javascript // } } function mousePressed(){ mouseWasPressed = true }si no desea la "animación", puede usar su método anterior, pero cambie el 0.05 a 1:
for(let i = 0; i <= width; i ++) // you don't have to add parentheses for 1 line x ++; // x = x + 1 just a shortening in javascriptO solo
x = width // or x += width (x = x + width)