Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
¿Cómo puedo cambiar la velocidad de un objeto en p5.js si se presiona el mouse en OOP?

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.


Solución

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.


Otros pensamientos

Algunos otros pasos que tomé para ajustar su código a más condiciones de trabajo incluyen:

  1. Creé una función de reset() para usar en la función de setup() y potencialmente capaz de restablecer la animación cuando lo desee.
  2. Cambié la declaración de la variable rad a const rad = 50 ya que no cambia
  3. Cambié el constructor de Ball para incluir las coordenadas iniciales (x, y) al crear la bola (podría ser útil si se crean varias bolas)
    • Si desea crear un número arbitrario de bolas, cree una matriz y use array.push(new Ball(x, y)) para cada bola y recorra la matriz para move() / bounce() / body() cada bola .
  4. Asumo que 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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda