Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
How can I change an object's speed in p5.js if the mouse is pressed in OOP

Hi guys i'm very new to p5/js and not quite good at OOP programming.

I want to drop a ball by changing its speed once the mouse is clicked. After trying to write and edit the code many times, the p5 editor didn't show any error massages but there aren't anything shown up on the display. So, I need a hand and some advices to fix this kind of problem.

Thank you in advance (:

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 Respostas
Responde à pergunta

0

You've got some good beginnings to your code. I modified it just a bit to assist toward OOP programming. See the code at the end of my answer for the full source.


Solution

The main question you are asking involves setting the ball's speed when the mouse button is pressed. For that, you should declare a mousePressed() function in your code as such (borrowing from your if block):

function mousePressed() {
  // if the mouse is pressed
  // set the new speed;
  ball.xspeed = 1.5;
  ball.yspeed = 1.5;
}

That should set the speed of the ball and that should solve your problem.


Other thoughts

Some other steps I took to adjust your code to more working conditions include:

  1. I created a reset() function to be used in the setup() function and potentially able to reset the animation whenever you would like.
  2. I changed the rad variable declaration to const rad = 50 since it doesn't change
  3. I changed the Ball constructor to include initial (x, y) coordinates when creating the ball (could be helpful if creating multiple balls)
    • If you want to create an arbitrary number of balls, create an array and use array.push(new Ball(x, y)) for each ball and loop through the array to move()/bounce()/body() each ball.
  4. I'm assuming rad is meant to be the radius of the balls, so I set the this.w and this.h to rad * 2 since with and height would equate to the diameter.

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 Relatório

0

Numbers before code are line numbers, they might be wrong, but should be close enough...

  • You need to move the 64 if(mouseIsPressed){} into a function like 47 move().

  • Also you haven't declared and initialized 39 this.xdirection in the constructor(){}.

  • I think 67 this.fill(0, 0, 0) should be fill(0).

  • Maybe 24 ball1.body(); should be after the other methods (24 -> 26 line).

  • I think the if() statements in bounce(){} are wrong, since they'd need to have AND or && instead of OR or ||.

Also you might want to make the if(mouseIsPressed) into function mousePressed(){} mouseIsPressed is a variable that is true if mouse button is down; mousePressed is a function that gets called once when user presses the mouse button.

function mousePressed(){
   ball1.xSpeed = 1.5
   ball1.ySpeed = 1.5
}

There might very well be other things i haven't noticed.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda