Hola chicos, soy muy nuevo en p5/js y no soy muy bueno en programación orientada a objetos.
Quiero dejar caer una pelota cambiando su velocidad una vez que se hace clic con el mouse. Después de intentar escribir y editar el código muchas veces, el editor p5 no mostró ningún mensaje de error, pero no se muestra nada en la pantalla. Entonces, necesito una mano y algunos consejos para solucionar este tipo de problema.
Gracias de antemano (:
let ball1; let circleX = 50; let circleY = 50; let xspeed = 0; // Speed of the shape let yspeed = 0; // Speed of the shape let xdirection = 1; // Left or Right let ydirection = 1; // Top to Bottom let rad =50; function setup() { createCanvas(400, 400); ball1 = new Ball(); } function draw() { background(220); ball1.x =20; ball1.y = 50; ball1.c = color(25,0,100) ball1.body(); ball1.move(); ball1.bounce(); } class Ball { constructor(){ this.x = width/2; this.y = height; this.w = 30; this.h = 30; this.c = color(0,255,0); this.xspeed = 0; this.yspeed = 0; } body(){ noStroke(); fill(this.c); ellipse(this.x, this.y, this.w, this.h); } move() { //this.xpos = width / 2; //this.ypos = height / 2; this.x = this.x + this.xspeed * this.xdirection; this.y = this.y + this.yspeed * this.ydirection; } bounce() { if (this.x > width - rad || this.x < rad) { this.xdirection *= -1; } if (this.y > height - rad || this.y < rad) { this.ydirection *= -1; } } if(mouseIsPressed) { // if the mouse is pressed //set the new speed; this.fill(0, 0, 0); this.xspeed =1.5; this.yspeed=1.5; } }Tienes algunos buenos comienzos para tu código. Lo modifiqué un poco para ayudar en la programación OOP. Vea el código al final de mi respuesta para la fuente completa.
La pregunta principal que está haciendo implica establecer la velocidad de la pelota cuando se presiona el botón del mouse. Para eso, debe declarar una función mousePressed() en su código como tal (tomando prestado de su bloque if ):
function mousePressed() { // if the mouse is pressed // set the new speed; ball.xspeed = 1.5; ball.yspeed = 1.5; }Eso debería establecer la velocidad de la pelota y eso debería resolver tu problema.
Algunos otros pasos que tomé para ajustar su código a más condiciones de trabajo incluyen:
reset() para usar en la función de setup() y potencialmente capaz de restablecer la animación cuando lo desee.rad a const rad = 50 ya que no cambiaBall para incluir las coordenadas iniciales (x, y) al crear la bola (podría ser útil si se crean varias bolas)array.push(new Ball(x, y)) para cada bola y recorra la matriz para move() / bounce() / body() cada bola .rad está destinado a ser el radio de las bolas, así que configuré this.w y this.h en rad * 2 ya que with y height equivaldrían al diámetro. let ball; const rad = 50; // let circleX = 50; // let circleY = 50; //let xspeed = 0; // Speed of the shape //let yspeed = 0; // Speed of the shape function setup() { createCanvas(400, 400); reset(); } function draw() { background(220); ball.body(); ball.move(); ball.bounce(); } function mousePressed() { // if the mouse is pressed //set the new speed; ball.xspeed = 1.5; ball.yspeed = 1.5; } function reset() { ball = new Ball(width / 2, height / 2); } class Ball { constructor(x, y) { this.x = x; this.y = y; this.w = rad * 2; this.h = rad * 2; this.c = color(25, 0, 100); this.xspeed = 0; this.yspeed = 0; this.xdirection = 1; this.ydirection = 1; } body() { noStroke(); fill(this.c); ellipse(this.x, this.y, this.w, this.h); } move() { this.x = this.x + this.xspeed * this.xdirection; this.y = this.y + this.yspeed * this.ydirection; } bounce() { if (this.x > width - rad || this.x < rad) { this.xdirection *= -1; } if (this.y > height - rad || this.y < rad) { this.ydirection *= -1; } } } <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>Los números antes del código son números de línea, pueden estar equivocados, pero deberían estar lo suficientemente cerca...
Debe mover el 64 if(mouseIsPressed){} a una función como 47 move() .
Además, no ha declarado e inicializado 39 this.xdirection en el constructor(){} .
Creo que 67 this.fill(0, 0, 0) debería ser fill(0) .
Quizás 24 ball1.body(); debe estar después de los otros métodos (24 -> 26 líneas).
Creo que las declaraciones if() en bounce(){} son incorrectas, ya que necesitarían tener AND o && en lugar de OR o || .
También es posible que desee convertir if(mouseIsPressed) en function mousePressed(){} mouseIsPressed es una variable que es verdadera si el botón del mouse está presionado; mousePressed es una función que se llama una vez cuando el usuario presiona el botón del mouse.
function mousePressed(){ ball1.xSpeed = 1.5 ball1.ySpeed = 1.5 }Es muy posible que haya otras cosas que no he notado.